SoFunction
Updated on 2025-04-07

The problem of vue's proxy configuration pathRewrite rewrite not taking effect and its solution

Proxy configuration pathRewrite rewrite does not take effect

I didn't see what I encountered when I searched online.

    devServer: {
        proxy: {
            //Proxy matches prefix 2            '/api2': {
                target: 'http://localhost:5001',
                pathRewrite: {'^/api2': ''},
                ws: true,
                changeOrigin: true
            },
            //Proxy matches prefix 1            '/api': {
                target: 'http://localhost:5000',
                pathRewrite: {'^/api': ''},
                ws: true,)
                changeOrigin: true
            }
        }
    }

At the beginning, the proxy with /api prefix was configured, and there was no problem. Then the proxy with /api2 prefix was configured, and then the proxy with /api2 prefix was not accessible.

Reason: Because /api is in front, it first matches /api, for example, accessing /api2/test. Since /api first matches /api, after rewriting /api as an empty string, the path becomes 2/test, which is naturally wrong.

Solution: Put /api2 in front of /api, let api2 match first, or name it /api2, so that it cannot match /api first

webpack proxy---pathRewrite

I encountered a problem today, assuming that the project is that I have a backend locally, with different port numbers, front-end 4000, back-end 3100, and request method 4000 proxy to 3100

Proxy to local

The interface request method is as follows

http://localhost:4000/api/scoringrules/all   //Each request is followed by/api

Configuration:

"proxy": {
    "/api": {
      "target": "http://localhost:3100",
      "changeOrigin": true,
      "pathRewrite": {     // If the interface itself does not have /api, you need to rewrite the address through pathRewrite, here convert /api to '        "^/api": ""
      }
    }
  },

pathRewrite: Rewrite path

When the backend recognizes /api is replaced with empty, the backend does not have /api

/api is just a way to distinguish routes and interfaces

Whether to configure pathRewrite depends on the request method of the front-end and the acceptance method of the back-end

ps:

For example: When I configure the local

When the front-end requests parameters, there is /api to distinguish between web pages and interfaces, but the background does not accept them, so the configuration is required as above.

However: When I configure the domain name, the domain name interface address is with /api, so there is no need to configure pathRewrite at this time

The above is personal experience. I hope you can give you a reference and I hope you can support me more.