在同一端口上运行前端和后端 [英] Running frontend and backend on the same port

查看:1573
本文介绍了在同一端口上运行前端和后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a problem today that has something to do with routing. I have two main codes: one is the frontend and the other one is the backend.

前端是使用 Vue.js 编写的,因此它是 SPA .该Web应用程序非常复杂,涉及许多路由和后端 AJAX API调用.

The frontend is written using Vue.js so it's a SPA. This webapp is kind of complex and involves a lot of routing and backend AJAX API calls.

// 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/>'
})

后端是在 Node.js 上使用 Express 编写的,它可以回答 Front 中特定的 AJAX 调用>.

The backend is written using Express on Node.js and it answers to specific AJAX calls from the Frontend.

// 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");
});

我只在开发过程中使用了此设置,所以我都同时在本地主机上运行两者,并且两者都使用不同的端口.现在,我想开始生产周期,但是我不知道从哪里开始.

I only used this setup during development so I had both running at the same time on localhost with a different port for both. Now I would like to start the production cycle but I have no idea where to start.

最重要的是,我将两个应用程序都部署到在外部服务器上运行的 V 虚拟 M 机器上.它已经有一个DNS关联和一个静态IP地址,因此已经涵盖了. 当我尝试在此生产计算机上同时运行两个程序时,会出现问题,因为它的开放端口仅是端口 80 和端口 443 .我认为这在生产环境中非常正常,但是我不知道如何调整我的应用程序,以使它们仍然可以相互对话并在仍然使用单个端口的情况下从数据库中检索有用的信息

Most importantly I am deploying both applications onto a Virtual Machine that is running on an external server. It already has a DNS association and a static IP address so that is already covered. The problem arises when I try to run both programs at the same time on this production machine since its open ports are only the port 80 and the port 443. I think this is pretty normal in a production environment but I don't know how to adapt my applications so that they can still talk to each other and retrieve useful information from the Database while still using a single port.

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

I hope I explained the problem kinda well. Looking forward to a nice (and maybe long) answer.

推荐答案

我建议内部在端口3000上运行后端,并让nginx侦听80和443,并将以'/api'开头的url代理到3000并交付前端,因为它只是一堆静态文件.

I'd recommend running the backend on port 3000 internally and have nginx listening on 80 and 443 and proxying urls starting with '/api' to 3000 and deliver the frontend directly since it's just a bunch of static files.

这将是您的nginx配置.只要确保后端服务器具有一些api前缀(如"/api")即可.使用"npm run build"构建您的vuejs应用,并将文件夹复制到/opt/frontend.

This would be your nginx configuration. Just make sure backend server has some api prefix like '/api'. Build your vuejs app with 'npm run build' and copy the folder to /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;
    }
}

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

Alternatively, you could use the backend to host the frontend. However, a webserver like nginx is more efficient at serving static files than your backend api server.

这篇关于在同一端口上运行前端和后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆