首页 > 解决方案 > axios 中的 GET/POST 不工作,但 fetch 工作

问题描述

我在 heroku 上托管了一个 REST API。它由 Express、NodeJS 和 MongoDB(mongoose as orm 和 MongoDB Atlas)组成。我正在使用 MERN 堆栈。初学者在这里

API 链接:/api/todos

该 API 与 Postman 和 VS code 的 API 插件一起工作得很好。它在本地主机上也可以正常工作。

但是当我尝试使用 axios 进行 GET/POST 时,它给出了Error: "Network Error" 但是fetch()工作得很好。邮递员也是如此。

我还在控制台中看到了 cors 警告:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mern-deploy-test-adib.herokuapp.com/api/todos. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)

但我这样设置cors: app.use(cors({ origin: 'http://localhost:3000/', credentials: true }))

有趣的是,该 API 在 localhost 中工作,但在部署后它不适用于 axios。

我已经设置cors origin: 'http://localhost:3000/' 并且我检查了 fetch 和 axios GET 请求的标头。它们实际上是相同的。

请求头有Access-Control-Allow-Origin http://localhost:3000/

顺便说一句,我的前端托管在 localhost:3000

那么为什么会这样呢?为什么 axios 不工作但 fetch 工作。

编辑:这是 axios 和 fetch 请求的代码。

//fetch
fetch(`https://heroku-api-link/api/todos`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))

//axios
axios.get(`https://heroku-api-link/api/todos`)
.then(data => console.log(data))
.catch(err => console.log(err))

EDIT#2:我使用手机上的编辑器(SPCK 编辑器)尝试了 axios 请求。请求成功。我只是不明白为什么它不能在我的电脑上工作。

标签: javascriptajaxapiaxiosfetch

解决方案


我终于想通了!!实际上这是我在 cors 中设置的原始链接。我将原点设置为http://localhost:3000/. 但有趣的是,客户端来源(也http://localhost:3000/)与服务器中的来源不匹配。但是,当我将服务器 cors origin 更改为 时http://localhost:3000,从 origin 中删除'/'解决了这个问题。我不知道为什么它没有奏效,但我很高兴它奏效了。现在我需要解释它为什么起作用。跟具体路线有关系吗?就像添加'/'使得只有“家”路线可以工作?


推荐阅读