【问题标题】:Network Error / 403 Forbidden on request to a service React JS axios proxy网络错误/403 Forbidden on request to a service React JS axios proxy
【发布时间】:2020-07-22 20:51:48
【问题描述】:

我需要制作一个 React 应用程序,该应用程序向该服务 https://www.indecon.online/last 发出一个 Job 申请请求,我目前在尝试发出 GET 请求时遇到问题。

它在浏览器或 Postman 中运行良好,但在使用 axios 时,情况就不一样了。

起初我尝试用 axios 发出一个简单的 GET 请求,如下所示:

我得到了这个错误:

Access to XMLHttpRequest at 'https://www.indecon.online/last' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

所以,我尝试了第二次,这次使用 http-proxy-middleware npm 包(按照本教程:https://levelup.gitconnected.com/overview-of-proxy-server-and-how-we-use-them-in-react-bf67c062b929)。 我像这样配置了一个 setupProxy.js 文件:

然后像这样简单地更改异步函数:

现在我在请求之后收到此错误(第二个是 catch 块内的 console.error() 的结果):

GET http://localhost:3000/last 403 (Forbidden)

ERROR:  Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)

我已经用另一个公共服务尝试了代理配置和 axios 请求,并得到了成功的响应。

感谢您的帮助!

【问题讨论】:

    标签: reactjs proxy cors axios http-status-code-403


    【解决方案1】:

    我假设您使用 create-react-app 创建了应用程序,因此您有一个 package.json,它依赖于 react-scripts 和一个使用 react-scripts 的启动脚本。您可以从项目中删除 http-proxy-middleware 包并在 package.json 中添加代理条目:

    {
      "dependencies": {
        "react-scripts": "3.4.1", <-- you should already have this
      },
      "scripts": {
        "start": "react-scripts start", <-- you should already have this
      },
      "proxy": "https://www.indecon.online"
    }
    

    现在在你的反应代码中你可以做axios.get('/last')

    使用 npm 或 yarn start 启动您的项目。

    如果它不起作用,那么您能否在问题中发布您的 package.json(不是图片,但请复制粘贴文本)。

    这个答案也是你在问题中提到的in the documentation

    【讨论】:

    • 成功了。老实说,尽管这两种方法(设置 setupProxy 并直接在 package.json 中添加代理)的工作方式相同,所以我没有尝试第二种方法。非常感谢。
    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2012-01-30
    相关资源
    最近更新 更多