如何使用 Node 运行 后端服务器?

How to run a backend server with Node?

我正在学习 Vue.js 并且从基本模板 vue init webpack my-project,我想要一个后端 运行ning。

前端使用 webpack 启动,但我的 server.js 文件必须使用 node server.js 单独启动。我怎样才能一起启动它们?

我搜索了一些基本的例子,但是很难找到。

目前我的 package.json 中有这个:

{
  "scripts": {
    "client": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",

    "server": "nodemon src/server/server.js --exec babel-node"
  },
  // ...
}

这很好,但是客户端和服务器 运行 在不同的端口上。在生产应用程序中,我只需要使用一个端口。

怎么可能?

尝试PM2

PM2 是一个进程管理工具,用于启动、停止和监视 Node JS 应用程序。

阅读本指南如何同时 运行 Express 和 Webpack Dev Server。

Simultaneously Running Express and Webpack Dev Server

这有点意见但是;理想情况下,您的前端和后端应该分开存在。但是,如果您发现从一个开始另一个开始的组合代码库更容易,您可以考虑利用 webpack-dev-middleware.

当你说你有单独的 server.js 文件时,听起来你希望能够从 webpack 设置的服务器上挂起额外的中间件。 webpack-dev-middleware 公开一个服务器供您在上面挂任何您想要的中间件,这意味着 1 个服务器而不是 2 个节点实例。

我以前尝试过这样做,但我 运行 遇到的主要问题是,如果我对我的实际服务器进行了更改,我将需要重新启动 webpack,这可能需要一段时间才能真正启动,但在使用热重新加载时速度要快得多,因为整个过程不会不断重新启动。

请注意,除非您使用像 nuxt 这样的东西,否则您的前端在您 运行 npm build 之后将只是静态内容。您不会 运行 宁 webpack 投入生产。

生产环境中

这是我常用的部署策略

I use Nginx as a static web server and HTTP proxy

I use pm2 to mange node API

PM2 是一款出色的流程管理器工具,具有多项功能

So what you need to is build (probably npm run build) your vue js app then you will get your static assets a dist/build folder containing just static content with index.html as an entry point

像下面这样用 pm2 启动你的节点服务器

pm2 start server.js --name='api'

这是代理节点 API 并提供在 /etc/nginx/sites-available/default

处找到的静态内容的示例 Nginx 配置
server {
    listen *:80;

    server_name localhost; ## could be  www.yourdomain.com

    location / {
          root /home/me/myapp/dist; # your app build path
          try_files $uri index.html;
      }
    location /api {
        proxy_pass http://localhost:5678/api;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_connect_timeout 600000;
        proxy_send_timeout 600000;
        proxy_read_timeout 600000;
        send_timeout 600000;

        gzip on;
        gzip_proxied any;
        gzip_types
            application/json;

    }

So what you basically get is your Vue app at port 80 the default so you don't have to specify the port and your API will be at /api so your vue app will be at youdomain.com and the API at youdomain.com/api

在开发环境中

我通常不介意使用两个命令启动我的 API 和前端。 我因此在单独的终端中启动它们以单独调试和开发。

if you really care about starting them in the single command

您可以在 package.json

中创建一个新命令
"start":"npm run server && npm run client"