NodeJs Express服务器代理和托管静态内容

时间:2019-08-16 00:28:27

标签: node.js express

我正在尝试使用expressjs创建一个Nodejs服务器来服务我的静态React内容。如果您是代理路径,我该如何实现,否则代理返回index.html。当前代码如下:

const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, 'build');
var proxy = require('http-proxy-middleware');

app.use(express.static(publicPath));

app.use('/pcs', proxy('/pcs',
    {
      target: '<target>',
      changeOrigin: true,
      pathRewrite: {'^/pcs': ''},
      hostRewrite: 'localhost:3000',
      protocolRewrite: 'http'
    }));

app.get('*', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'));
});

app.listen(3000, () => {
  console.log('Server is up!');
});

1 个答案:

答案 0 :(得分:0)

您将要使用一种模式来匹配代理路径,否则它将仅匹配确切的“ / pcs”路径。这是一种模式,可匹配以“ / pcs /”开头的任何路由(除了“ / pcs”以外):

app.use('/pcs/?*', proxy('/pcs', 
  {
    target: '<target>',
    changeOrigin: true,
    pathRewrite: {'^/pcs': ''},
    hostRewrite: 'localhost:3000',
    protocolRewrite: 'http'
  }));