部署一个需要 expressjs 支持客户端路由的项目。

本地运行

在本地把基本环境跑起来:

npm run build

然后 build 文件夹内添加 server.js 如下


var express = require('express');
var app = express();
var path = require('path')

app.use(express.static('.'))


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

app.listen(3010, function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3010');
});

部署到服务器

mv build my-project
scp -r my-project haoduoshipin.com:sites

打开 tmux ,跳转到 sites/my-project

npm start

然后,添加 nginx 配置文件,/etc/nginx/sites-enabled/my-project.conf

server {
    listen     80;
    server_name mt.haoduoshipin.com;

    location / {
        proxy_pass http://localhost:3010;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_x_forwarded_host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 3m;
        proxy_send_timeout 3m;
    }
}

重启 nginx

sudo service nginx reload

尝试用 serve

服务器上我们也来尝试一下使用 serve 来部署。

npm i -g serve
serve -s build

结语

完工。上面有些步骤肯定是有待改进的,不过暂时够用就好。