【问题标题】:Why can't export/import const app = express to another js file为什么不能导出/导入 const app = express 到另一个 js 文件
【发布时间】:2018-03-28 00:04:47
【问题描述】:

我正在尝试分离职责,将我将在服务器端的应用程序中执行的不同操作划分到不同的文件和模块中。

我遇到了一个我无法理解的问题。我尝试从启动服务器的文件中导出变量app,我以以下方式在其中存储express

server.js

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
import path from 'path';

const app = express();

app.set('port', process.env.PORT || 3000);

app.use(webpackDevMiddleware(webpack(webpackConfig)));

app.get('*', (req, res) => { 
    res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});

app.get('/api', (req, res) => {
    res.json({api: "Woks Fine"});
});

app.listen(app.get('port'), () => {
    console.log("App Start in Port", app.get('port'));
});

export default app;

apiGoogleMaps.js

import app from '../server.js';

export function respuestaMensaje(apiUrl, app) {
    console.log(apiUrl);
    app.post(apiUrl, (req, res) => {
        console.log(req.body);
    });
}

地址js

import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import { respuestaMensaje } from '../../../src/handlers/apiGoogleMap.js';


class AddressInput extends Component{

    constructor(){    
        super();
        this.state = {
            address: "",
            api:"http://maps.google.com/maps/api/geocode/json?address=",
            direccion: "",
            latitud: "",
            longitud:""
        };
    } 

    render(){
        return(
            <div> 

                <form>                
                    <input type="text" value={this.state.address} onChange={this.updateAdress.bind(this)}/>
                    <button onClick={this.getAddressGeo.bind(this)}>Consultar</button> 
                </form>

                <ul>
                    <li><label>Direccion:</label>{this.state.direccion}</li>
                    <li><label>Latitud:{this.state.latitud}</label></li>
                    <li><label>Longitud:{this.state.longitud}</label></li>
                </ul>
            </div> 
        )
    }

    updateAdress(event){
        this.setState({
            address: event.target.value
        });
    }

    getAddressGeo(e){

        e.preventDefault();
        const apiUrl = this.state.api + this.state.address;
        respuestaMensaje(apiUrl);
    } 
}

export default AddressInput;

项目结构

出现很多这样的错误:

[1] WARNING in ./node_modules/uglifyjs-webpack-plugin/node_modules/uglify-es/tools/node.js
[1] 18:11-32 Critical dependency: the request of a dependency is an expression
[1]  @ ./node_modules/uglifyjs-webpack-plugin/node_modules/uglify-es/tools/node.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/uglify/minify.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/uglify/index.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/index.js
[1]  @ ./node_modules/uglifyjs-webpack-plugin/dist/cjs.js
[1]  @ (webpack)/lib/WebpackOptionsDefaulter.js
[1]  @ (webpack)/lib/webpack.js
[1]  @ ./src/server.js
[1]  @ ./src/handlers/apiGoogleMap.js
[1]  @ ./src/ui/components/address.js
[1]  @ ./src/ui/app.js
[1]  @ ./src/ui/index.js
[1]

Full error log

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    这个错误是由server.js中的webpack导入引起的,用作中间件:

    import webpack from 'webpack';
    import webpackDevMiddleware from 'webpack-dev-middleware';
    import webpackConfig from '../webpack.config';
    import path from 'path';
    
    const app = express();
    
    app.set('port', process.env.PORT || 3000);
    
    app.use(webpackDevMiddleware(webpack(webpackConfig)));
    

    堆栈跟踪中的明显帧是:

    [1]  @ (webpack)/lib/WebpackOptionsDefaulter.js
    [1]  @ (webpack)/lib/webpack.js
    [1]  @ ./src/server.js
    

    由于 webpack 使用动态导入,您似乎不能将 webpack 包含在 webpack 包中,至少不能通过导入来包含它。

    express(特别是express.view)也会出现同样的错误,在this issue 中有解释:

    ExpressJS 中有一个动态需求:https://github.com/expressjs/express/blob/master/lib/view.js#L78

    您可以将express(和/或webpack)标记为external dependency,以防止它们被包含在捆绑包中(我没有使用过这个库,它与问题相关联)。

    【讨论】:

    • 现在,显示,app.post(apiUrl, function (req, res) { [0] ^ [0] [0] TypeError: Cannot read property 'post' of undefined
    • 这是一个不同的(可能不相关的)问题。检查新错误范围内app的类型,由于某种原因它没有被加载。
    • 你有理由,至少其他问题没有发生
    【解决方案2】:

    不要导出整个服务器的主要骨干应用,而是在 apiGoogleMaps.js 文件中使用路由器并将其导出。

    成功使用app.js 文件中的路由器! :D

    birds.route.js

    var express = require('express')
    var router = express.Router()
    
    router.get('/', function (req, res) {
        res.send('Birds home page')
    })
    router.get('/:id', function (req, res) {
        res.send(req.params.id);
        })
    module.exports = router
    

    app.js

    const myBirds = require('./birds');
    ...
    ...
    app.use('/birds', myBirds);
    

    【讨论】:

    • 但是问题发生在apiGoogleMaps,无法导入app,不管怎样,我会尝试,稍后再回答
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多