【问题标题】:Node with Vue, different ports for requests and API带有 Vue 的节点,请求和 API 的不同端口
【发布时间】:2020-05-29 05:50:30
【问题描述】:

我有一个基于node的项目,前端有Vue。

在我的节点中的 app.js 文件中

if(process.env.NODE_ENV === 'production'){
    //static folder
    app.use(express.static(path.join(__dirname,'public'))); 
    //handle SPA
    app.get(/.*/, (req, res)=>{
        res.sendFile(__dirname + '/public/index.html');
    });
}

然后

const port = process.env.PORT || 4000;
app.listen(port, ()=>{
    console.log('Server runs on port ', port);
});

因此,节点监听端口 4000,所有传入请求(来自端口 4000)都转到 '/public/index.html' 以由 vue 提供服务

在我的vue.config.js 我有

const path = require('path');

module.exports = {
    outputDir : path.resolve(__dirname, '..public'),
    devServer:{
        proxy:{
            '/*':{
                target:'http://localhost:5000'
            }
        }
    }
}

目前一切正常,但请帮助我理解以下内容

如何让节点监听一个端口(例如 80),然后在另一个端口(例如 4000)中监听所有其他节点 API 端点?

我希望所有传入的请求都转到端口 80,然后仍然转到'/public/index.html',这样 Vue 就可以接管了。

但是,Vue 用于 GET 和 POST 数据的节点端点,我希望它们仍然在端口 4000,const basicUrl = 'http://awesomeness:4000/';

我该怎么做?

谢谢

【问题讨论】:

    标签: node.js express vue.js routes port


    【解决方案1】:

    您可能需要创建2个express App,如下链接所示:

    NodeJS Express - separate routes on two ports

    第一个会监听80端口,会返回index.html文件。

    另一个将监听 4000 并处理来自您的 Vue 应用程序的请求。

    【讨论】:

    • 这是个好主意,想想看,但是一台带有两个端口的 http 服务器怎么样?节点可以以某种方式做到这一点吗?
    • 似乎一个 servr 只能监听一个端口,所以每次你想处理不同的端口时,你都必须创建新的服务器(基本节点 js)/应用程序(expressJs)。然而,您可以在同一个文件中创建它们。因此,您可以拥有一个 nodeJs 脚本,该脚本可以通过不同的“服务器”/“应用程序”处理多个端口。
    猜你喜欢
    • 2015-03-09
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2017-08-08
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多