如何使用webpack代理devserver路径重写?

问题描述 投票:0回答:3

我目前正在努力重写 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,应该重新写入http://localhost:3000/MySite1/api

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

javascript angular webpack webpack-dev-server webpack-4
3个回答
10
投票

尝试以下操作:

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;
     },
  }
}

7
投票

创建 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

0
投票

我正在使用这样的设置

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        publicPath: 'http://localhost:8080/dist/',
        disableHostCheck: true,
        proxy: [
            {
                context: ['/api'],
                target: 'http://localhost:3000',
                pathRewrite: { '(/api)': '/MySite1$1' },
                secure: false,
            },
        ],
    },
© www.soinside.com 2019 - 2024. All rights reserved.