1.项目安装http-proxy-middleware
npm install http-proxy-middleware
2.src下新建setupProxy.js文件
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware('/api1',{ //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
target: 'http://0.0.0.0:8000', //配置转发目标地址(能返回数据的服务器地址)
changeOrigin: true, //控制服务器接收到的请求头中host字段的值
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000
changeOrigin默认值为false,但我们一般将changeOrigin值设为true
*/
pathRewrite: {'^/api1': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
}),
);
app.use(
createProxyMiddleware('/api2',{ //api2是需要转发的请求(所有带有/api2前缀的请求都会转发给5000)
target: 'http://0.0.0.2:32154', //配置转发目标地址(能返回数据的服务器地址)
changeOrigin: true, //控制服务器接收到的请求头中host字段的值
pathRewrite: {'^/api2': ''} //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
}),
);
}
3.暴露项目配置文件
项目文件夹下执行
npm run eject
若报错Remove untracked files, stash or commit any changes, and try again.
需要先添加git环境
git add .
git commit -m "show ejecting"
然后再执行npm run eject后会多出config以及scripts文件夹
4.修改start.js文件
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
require('../src/setupProxy')(devServer); ##新增这句
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});