在 Webpack 代理中删除匹配的 `/api` 路径

Remove matched `/api` path in Webpack proxy

我在 http://localhost:9090/ 有一个后端服务 运行。所有以 /api/* 开头的呼叫都应转发给它,前面没有 /api。所以当我调用 http://localhost:8080/api/my/route 它应该代理到 http://localhost:9090/my/route.

如果我使用以下选项:

proxy : [{
  path : '/api/*',
  target : 'http://localhost:9090'
}]

调用http://localhost:8080/api/my/route时,后端服务报错找不到路由/api/my/route

文档建议我可以使用 node-http-proxy 中的任何选项,但我想不出要使用的正确选项。

我需要使用哪些选项才能获得所需的结果?

EDITED 版本 <= 1.14.1 您可以使用选项 'rewrite'。这是一个将为匹配模式的每个请求调用的函数(例如:'/api/*')。该函数必须匹配签名 function (req,proxyoptions) { }

像这样:

proxy : [{
  path : '/api/*',
  target : 'http://localhost:9090',
  // bypass
  rewrite: function(req, options) {
    // manipulate req here 
    // in your case I think it's removing the /api part of url
  }
  // 
}]

自 webpack-dev-server version >= 1.15.0 起,您可以使用记录的 pathRewrite:

proxy: {
  '/api': {
    target: 'https://other-server.example.com',
    pathRewrite: {'^/api' : ''}
  }
}