在同一端口上运行前端和后端

Eug*_*nio 1 production node.js express vue.js

我今天遇到的问题与路由有关.我有两个主要代码:一个是前端,另一个是后端.

前端是使用Vue.js编写的,所以它是SPA.这个webapp很复杂,涉及很多路由和后端AJAX API调用.

// All imports
import ...

loadMap(Highcharts);
loadDrilldown(Highcharts);
boost(Highcharts);

Vue.config.productionTip = false

Vue.use(VueCookie);
Vue.use(ElementUI, {locale});
Vue.use(VueRouter);
Vue.use(VueHighcharts, {Highcharts });
Vue.use(HighMaps);

// This is a global component declaration
Vue.component('app-oven', Devices);
Vue.component('app-sidebar', SideBar);
Vue.component('app-header', Header);
Vue.component('app-footer', Footer);
Vue.component('app-query', Query);
Vue.component('app-deviceproperties', DeviceProperties);
Vue.component('app-device', Device)
Vue.component('app-queryselection', QuerySelection)
Vue.component('app-index', Index)
Vue.component('app-index', Error)
Vue.component('app-realtime', RealTime);
Vue.component('app-login', Login)
Vue.component('app-preferences', Preferences)

const routes = [
  { path: '/index', component: Index},
  { path: '/', component: Login},
  { path: '/device/:deviceId', component: Device},
  { path: '/preferences', component: Preferences},
  { path: '*', component: Error}
];

const router = new VueRouter({
  routes: routes,
  mode: "history" // Gets rid of the # before the path
})

new Vue({
  el: '#app',
  router: router,
  components: { App },
  template: '<App/>'
})
Run Code Online (Sandbox Code Playgroud)

后端是使用Express on Node.js编写的,它可以回答前端的特定AJAX调用.

// All imports
import ...

function prepareApp() {
    let app = new Express();

    app.use(cors({
        origin: "*",
        allowedHeaders: "Content-type",
        methods: "GET,POST,PUT,DELETE,OPTIONS" }));

    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

    app.use(helmet());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));

    // Get all parameters
    app.get('/params', params.parameters);
    // Get all devices ever seen on the databases
    app.get('/devices', params.devices);

    app.get('/organizeData', organizer.updateAll);

    // WebApp used services to access various things
    app.post('/customQuery', stats.query);
    app.post('/statistics', stats.statistics)
    app.post('/getUserInfo', stats.getUserInfo)
    app.post('/setUserInfo', stats.setUserInfo)
    app.post('/genericQuery', stats.genericQuery)
    app.post('/NOSQLQuery', stats.NOSQLQuery)

    // Users check and insertion
    app.get('/insertUser', stats.insertUser)
    app.post('/verifyUser', stats.verifyUser)

    app.get('/', errors.hello); // Returns a normal "hello" page
    app.get('*', errors.error404); // Catch 404 and forward to error handler
    app.use(errors.error); // Other errors handler

    return app;
}

let app = prepareApp();

//App listener on localhost:8080
app.listen(8080, () => {
    console.log("App listening on http://localhost:8080");
});
Run Code Online (Sandbox Code Playgroud)

我在开发过程中只使用了这个设置,所以我在localhost上同时运行了两个端口.现在我想开始生产周期,但我不知道从哪里开始.

更重要的是,我同时部署应用到V irtual 中号是一个外部服务器上运行achine.它已经具有DNS关联和静态IP地址,因此已经涵盖.当我尝试在这台生产机器上同时运行两个程序时出现问题,因为它的开放端口只是端口80和端口443.我认为这在生产环境中非常正常,但我不知道如何调整我的应用程序,以便他们仍然可以相互通信并从数据库中检索有用的信息,同时仍然使用单个端口.

我希望我能很好地解释这个问题.期待一个很好的(也许很长的)答案.

Kri*_*ris 8

我建议在内部在端口3000上运行后端,让nginx在80和443上监听,并将代码从'/ api'开始代理到3000并直接传递前端,因为它只是一堆静态文件.

这将是你的nginx配置.只需确保后端服务器有一些api前缀,如'/ api'.使用'npm run build'构建您的vuejs应用程序,并将该文件夹复制到/ opt/frontend.

upstream backend {
    server 127.0.0.1:3000;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    location /api/ {
        proxy_pass         http://backend;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }

    location / {
        root /opt/frontend/dist;
        try_files $uri $uri/ /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用后端来托管前端.但是,像nginx这样的网络服务器在提供静态文件方面比后端api服务器更有效.


小智 5

如果您没有办法打开更多端口,您可以将前端构建为生产模式,然后将其 index.html 和 dist 文件夹放入您的 nodejs 应用程序所在的同一文件夹中。然后,您创建一个侦听端口 80 的 Express 应用程序并发送 HTML 文件。

var express = require('express');
var app = express();
var path = require('path');
var dir = '//vm//path//here';

app.get('/', function(req, res) {
    res.sendFile(path.join(dir + '/index.html'));
});

app.listen(80);
Run Code Online (Sandbox Code Playgroud)