How to use webpack proxy devserver pathRewrite?

10,368

Solution 1

Try following:

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

Solution 2

Create proxy.config.json

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

the ^/api part will be replaced with target

and then start the app with

ng serve --proxy-config proxy.config.json
Share:
10,368
ANewGuyInTown
Author by

ANewGuyInTown

...

Updated on June 08, 2022

Comments

  • ANewGuyInTown
    ANewGuyInTown almost 2 years

    I'm currently struggling with rewriting the proxy path to the api server. In my setup what I do is for api request, I delegate it to the proxy server and only for js/html/css webpack-dev-server is used.

    Following is what I'm using:

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

    So, How do I append /MySite1 to api request before it proxies to the localhost:3000?

    E.g. If the request is : http://localhost:8080/api, it should re write to http://localhost:3000/MySite1/api

    Also, If the request is : http://localhost:8080, it should re write to http://localhost:3000/MySite1

  • ANewGuyInTown
    ANewGuyInTown almost 5 years
    I want to append /MySite1 before /api not ignore
  • Adrian Brand
    Adrian Brand almost 5 years
    Sorry was still editing my file to match yours, that should work
  • ANewGuyInTown
    ANewGuyInTown almost 5 years
    No, what I meant is if the request is localhost:8080/api, it should re write it to localhost:3000/MySite1/api