簡體   English   中英

NodeJs Express服務器代理和托管靜態內容

[英]NodeJs Express Server to Proxy and Host Static Content

我試圖用提供我的靜態React內容的expressjs創建一個nodejs服務器。 如果您是代理路徑,我該如何實現,否則代理返回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!');
});

您將要使用一種模式來匹配代理路徑,否則它將僅匹配確切的“ / pcs”路徑。 這是一種匹配任何以“ / pcs /”開頭的路由的模式(除了“ / pcs”以外):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM