【问题标题】:http-proxy-middleware does't catch request from react app to APIhttp-proxy-middleware 没有捕获从反应应用程序到 API 的请求
【发布时间】:2019-05-02 10:55:47
【问题描述】:

进入我的组件

axios.post('/api/' + 'create', {
  name: 'new name'
}, 
{
                headers:
                {
                    'Content-Type': 'application/json'
                }
}
)

进入 setupProxy.js ,根据第三方官方指令https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development创建

const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(proxy('/api/', {
        target: 'http://my-api.com/',
        changeOrigin: true
    }));
};

当我从我的应用程序中使用 axios 调用方法时 进入浏览器控制台写入 发布http://localhost:3000/api/create 404(未找到)

我尝试将 /api/* 和 /api/** 写入配置 http-proxy-middleware ,但没​​有帮助。

什么不工作?

【问题讨论】:

    标签: reactjs axios http-proxy-middleware


    【解决方案1】:

    请尝试使用下面的代码,http-proxy-middleware 版本1.0.0 以后,您不能使用代理作为名称。

    const { createProxyMiddleware } = require('http-proxy-middleware');
    module.exports = (app) => {
      app.use(createProxyMiddleware('/api',
      { target: 'http://localhost:3001/' 
      }));
    }

    注意:从此处的 PR 讨论之一中找到此内容:https://github.com/facebook/create-react-app/issues/8550

    【讨论】:

      【解决方案2】:

      我知道它已经很晚了,我遇到了同样的问题。保留对我有用的东西,以便其他人可以尝试。

      我代理了这个端点 - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json

      setupProxy.js

      const { createProxyMiddleware } = require('http-proxy-middleware');
      module.exports = (app) => {
          app.use(createProxyMiddleware('/api2', {
              target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
              changeOrigin: true,
              pathRewrite: { '^/api2': '' }
          })
          );
      }
      

      您的 .js 文件

      triggerCORSCall() {
          axios.get(`/api2/Customers?$format=json`)
            .then(response => {
              alert('Success');
            }).catch(error => {
              alert('Failure');
              console.log(error);
            })
        }
      

      【讨论】:

        猜你喜欢
        • 2018-10-22
        • 2020-12-22
        • 1970-01-01
        • 1970-01-01
        • 2021-04-08
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多