[英]NodeJs Express Server to Proxy and Host Static Content
I am trying to create a nodejs server with expressjs that serves my static react content. 我试图用提供我的静态React内容的expressjs创建一个nodejs服务器。 How do I implement to say if you are a proxied path, proxy else return index.html.
如果您是代理路径,我该如何实现,否则代理返回index.html。 Current code is below:
当前代码如下:
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!');
});
You'll want to use a pattern for matching the proxy path, otherwise it will only match the exact "/pcs" path. 您将要使用一种模式来匹配代理路径,否则它将仅匹配确切的“ / pcs”路径。 Here is a pattern to match any route starting with "/pcs/" (in addition to just "/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.