如何在webpack中使用createProxyMiddleware?

3
如何在 webpack 中使用 createProxyMiddleware?
我有一个带默认代理的 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


你想使用中间件而不是Webpack内置代理有特定的原因吗? - code
很难理解你在这里想要做什么。你是想让Webpack的开发服务器提供从不同服务器提供的代码数据,还是想发送API请求并将其重定向到你的API服务器? - code
抱歉留了太多注释,但我想提醒您出现错误是因为代理字段是为Webpack自己的代理配置的,而不是您可以手动设置的代理。 - code
@code 我想使用中间件,因为这个原因 - Learner
1个回答

1
据我所知,使用Webpack的开发服务器无法使用自定义中间件。如果你必须使用代理,可以将自定义的Express服务器挂钩到Webpack上,并使用中间件。

确保您还安装了expresswebpack-dev-middlewarewebpack-hot-middleware(如果您仍然想要HMR)。然后创建以下内容的服务器文件:

const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const webpack = require("webpack");
const webpackHotMiddleware = require("webpack-hot-middleware");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackConfig = require("./webpack.config"); // path to your `webpack.config.js`

const webpackCompiler = webpack(webpackConfig); // create webpack compiler with config

const app = express();
app.use(createProxyMiddleware(/* ... */));
app.use(webpackDevMiddleware(webpackCompiler, {
  publicPath: webpackConfig.output.publicPath, // provide the public path for the middleware
}));
// if you need HMR:
app.use(webpackHotMiddleware(webpackCompiler));

// you need "*" if you're creating a SPA like if you're using react router
app.get("*", (req, res) => {
  res.sendFile(/* absolute path to index.html */);
});

app.listen(3030, () => console.log("Webpack running on express server"));

为了让 HMR 正常工作,您需要稍微修改您的 webpack.config.js。将 config.entry 中的第二个和第三个元素替换为 "webpack-hot-middleware/client",然后在 config.plugins 中添加 new webpack.HotModuleReplacementPlugin()
现在使用 node server.js 启动您的服务器,并将 http://localhost:3030 视为普通的 Webpack 开发服务器 并祈求一切顺利
请记住,我们仅在开发环境中这样做。在生产环境中运行时不需要使用 webpack。
您的 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: [
      'webpack-hot-middleware/client', // this powers our HMR
      'react-hot-loader/patch', // activate HMR for React'
      './index.tsx', // the entry point of our app
    ],
    devServer: {
      port: 3030,
      hot: true, // enable HMR on the server
      historyApiFallback: true,
    },
    plugins: [new webpack.HotModuleReplacementPlugin()]
    // ... other code is omitted for the brevity
  })


谢谢回复!我应该保留还是删除 webpack.config.js 文件? - Learner
@Learner 注意保留。请注意稍微更改您的配置文件部分。 - code
请问您能否提供一个文件的示例吗?我真的不知道如何正确地编辑这个文件。 - Learner
谢谢你的回复!我稍后会检查它。非常抱歉,但是赏金已经过期了,但我将你的回复标记为答案。谢谢! - Learner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接