【问题标题】:Dynamic pathRewrite with createProxyMiddleware and create react app使用 createProxyMiddleware 重写动态路径并创建反应应用程序
【发布时间】:2021-04-29 23:58:45
【问题描述】:

根据https://create-react-app.dev/docs/proxying-api-requests-in-development/,我的 Create React App 中有以下内容

src/setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

这工作正常,并将所有请求发送到我在端口 5000 上运行的 nodejs 应用程序。但是我希望以某种方式拦截请求并将路径重写为 url 查询字符串格式。

我在 nodejs 服务器上运行 json-server,它需要对请求进行不同的格式化,使用这种格式 /api/cheeses?cheeseno=12

例如

'/api/cheese/12' => `/api/cheeses?cheeseno=12` 

我在此页面上遇到了pathRewriterouter https://www.npmjs.com/package/http-proxy-middleware,但我不知道如何映射它们。

稍后随着我的进步,我需要将嵌套路径路由映射到 url 查询。

所以

/location/{locationId}/aisle/{aisleid}/cheeses => /api/cheeses?locationId=12&aisleid=123`

谢谢

【问题讨论】:

    标签: javascript proxy create-react-app json-server http-proxy-middleware


    【解决方案1】:
    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    const rewriteFn = function (path, req) {
      return path.replace('/api/foo', '/api/bar');
    };
    
    const options = {
      target: 'http://localhost:3000',
      pathRewrite: rewriteFn,
    };
    
    const apiProxy = createProxyMiddleware('/api', options);
    

    rewriteFn 是关键

    https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md#custom-rewrite-function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 2022-08-22
      • 2019-06-26
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      相关资源
      最近更新 更多