如何在 webpack 中使用 createProxyMiddleware?
我有一个带默认代理的 webpack.config.js 文件:
我有一个带默认代理的 webpack.config.js 文件:
// development config
require('dotenv').config()
const package = require('../../package.json')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const commonConfig = require('./common')
const agent = require('agentkeepalive')
module.exports = (webpackConfigEnv, argv) =>
merge(commonConfig(argv), {
mode: 'development',
entry: [
'react-hot-loader/patch', // activate HMR for React
'webpack-dev-server/client?http://localhost:3030',
'webpack/hot/only-dev-server',
'./index.tsx', // the entry point of our app
],
devServer: {
port: 3030,
hot: true, // enable HMR on the server
historyApiFallback: true,
proxy: {
'/api/*': {
target: 'http://foobar:8080/',
secure: false,
changeOrigin: true,
agent: new agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 90000, // free socket keepalive for 90 seconds
}),
onProxyRes: (proxyRes) => {
var key = 'www-authenticate'
proxyRes.headers[key] =
proxyRes.headers[key] && proxyRes.headers[key].split(',')
},
},
},
},
// ... other code is omitted for the brevity
})
因为这个问题,我想使用http-proxy-middleware。
所以我将上面的配置文件修改为:
// ... other code is omitted for the brevity
proxy: createProxyMiddleware('/api/*', {
target: 'http://foobar:8080/',
secure: false,
changeOrigin: true,
agent: new agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 90000, // free socket keepalive for 90 seconds
}),
onProxyRes: (proxyRes) => {
var key = 'www-authenticate'
proxyRes.headers[key] =
proxyRes.headers[key] && proxyRes.headers[key].split(',')
},
}),
},
// ... other code is omitted for the brevity
})
然而,当我尝试构建我的应用程序时,它会抛出一个错误:
> [webpack-cli] webpack Dev Server Invalid Options
> options.proxy should be {Object|Array} (https://webpack.js.org/configuration/dev-server/#devserverproxy)
请告诉我如何在webpack配置中为代理应用createProxyMiddleware
?