如何使用webpack代理devserver pathRewrite?

How to use webpack proxy devserver pathRewrite?

我目前正在努力重写 api 服务器的代理路径。 在我的设置中,我所做的是针对 api 请求,我将其委托给代理服务器,并且仅针对 js/html/css webpack-dev-server 使用。

以下是我正在使用的:

devServer: {
    inline: true,
    port: 8080,
    historyApiFallback: true,
    publicPath: 'http://localhost:8080/dist/',
    disableHostCheck: true,
    proxy: {
        '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'???' : ''} //Need to append http://localhost:3000/MySite1/api
  }
}

那么,如何在代理到 localhost:3000 之前将 /MySite1 附加到 api 请求?

例如 如果请求是: http://localhost:8080/api, it should re write to http://localhost:3000/MySite1/api

此外, 如果请求是: http://localhost:8080, 它应该重新写入 http://localhost:3000/MySite1

创建proxy.config.json

{
  "/api/*": {
    "target": "http://localhost:3000/MySite1/api",
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

^/api部分将替换为target

然后使用

启动应用程序
ng serve --proxy-config proxy.config.json

尝试以下操作:

devServer: {
inline: true,
port: 8080,
historyApiFallback: true,
publicPath: 'http://localhost:8080/dist/',
disableHostCheck: true,
proxy: {
     '/api': {
     target: 'http://localhost:3000',
      pathRewrite: function(path, req) {
       var replacedPath = path;
       if (path.indexOf("MySite1") === -1) {
         replacedPath = replacedPath.replace("/", "/MySite1/api/");
       }
       return replacedPath;
     },
  }
}