如何使用HistoryAPI回退和代理远程api请求来设置webpack开发服务器?
我有一个react应用程序,它使用如何使用HistoryAPI回退和代理远程api请求来设置webpack开发服务器?,webpack,webpack-dev-server,Webpack,Webpack Dev Server,我有一个react应用程序,它使用react路由器,因此它使用HTML5历史API,我尝试将historyapi fallback设置为true来服务404条路径,为相同的index.html提供服务,而不是返回HTTP响应 这个单页应用程序向远程API服务器发出一些请求,这就是为什么我还需要将一些请求代理到我在开发过程中运行的express服务器。Web react应用程序在端口3000上提供服务,API在端口3001上运行 所以我试过: devServer:{ contentBase
react路由器
,因此它使用HTML5历史API,我尝试将historyapi fallback
设置为true
来服务404条路径,为相同的index.html
提供服务,而不是返回HTTP响应
这个单页应用程序向远程API服务器发出一些请求,这就是为什么我还需要将一些请求代理到我在开发过程中运行的express服务器。Web react应用程序在端口3000上提供服务,API在端口3001上运行
所以我试过:
devServer:{
contentBase: 'src/www', //Relative directory for base of server
devtool: 'eval',
hot: true, //Live-reload
inline: true,
port: 3000, //Port Number
host: 'localhost', //Change to '0.0.0.0' for external facing server
historyApiFallback: true,
proxy: {
'^\/users|sitters|bookings': {
target: 'http://127.0.0.1:3001',
rewrite: function(req) {
req.url = req.url.replace(/^\/api/, '');
}
}
}
},
devtool: 'eval',
output: {
path: buildPath, //Path of output file
filename: 'app.js'
},
因此,如果请求的路径以/users
或/sitters
或/bookings
开头,我想要的是点击远程api服务器,否则,请选择historyApiFallback
(serviceindex.html
)
当然,现在historyApiFallback总是为HTML文件服务,但我还需要代理才能工作。免责声明。这个答案可能已经过时了
在Express中间件中,堆栈顺序很重要。
代理应该先在webpack config中设置,然后再在historyApiFallback
中设置,它应该是这样的:
devServer:{
contentBase: 'src/www', //Relative directory for base of server
devtool: 'eval',
hot: true, //Live-reload
inline: true,
port: 3000, //Port Number
host: 'localhost', //Change to '0.0.0.0' for external facing server
proxy: {
'^\/users|sitters|bookings': {
target: 'http://127.0.0.1:3001',
rewrite: function(req) {
req.url = req.url.replace(/^\/api/, '');
}
}
},
historyApiFallback: true
},
当然,代理可以根据应用程序的需要更改为任何模式或正则表达式。就我而言,这正是我所需要的。我最终得到了以下解决方案:
const REMOTE_URL = process.env.REMOTE_URL || 'http://localhost:8090/';
const config = {
output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true,
contentBase: './app',
proxy: [{
context: '/api',
target: REMOTE_URL,
pathRewrite: {
'^/api' : '/'
}
}]
}
};
所以所有的请求都是http://locahost:port/api/
通过代理,并重写/api
例如http.get('/api/users')
转到just/users
顺便说一句,代理中的对象只是。我正在使用WebpackV4,并为
pathRewrite
insideproxy
添加适当的值,这对我来说很有效
例如,您在localhost:8080
上托管客户端,在localhost:3000
上托管API。然后,您的网页devServer
部分将如下所示
devServer: {
historyApiFallback: true,
proxy: {
'/graphql': {
changeOrigin: true,
pathRewrite: { '^/api': '' },
target: 'http://localhost:3000/api'
}
}
}
这似乎不再管用了。使用webpack 5.37.1,似乎不管devServer选项的顺序如何,都会首先加载代理。@Jitsusama是的。我的问题太老了。那是2016年