网络错误/ 403请求服务React JS axios代理禁止

问题描述 投票:0回答:1

我需要创建一个React应用程序,以向Job应用程序的此服务https://www.indecon.online/last发出请求,并且在尝试发出GET请求时,我目前遇到问题。

它在浏览器中或Postman内都可以正常工作,但是在尝试使用axios时,情况就不一样了。

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

enter image description here

我又得到了这个错误:

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文件:

enter image description here

并且仅更改了异步功能,如下所示:

enter image description here

现在我在请求后收到此错误(第二个是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个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.