【发布时间】:2021-07-04 08:34:34
【问题描述】:
我有一个托管在 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))
编辑#2: 我使用手机上的编辑器(SPCK 编辑器)尝试了 axios 请求。请求成功。我只是不明白为什么它不能在我的电脑上工作。
【问题讨论】:
-
请添加您的代码;对于两者,fetch 和 axios。
-
完成。只是一个基本的获取请求。
-
"它返回我在 server.js 中设置的 catch 块内的服务器错误" — 那是什么错误?
-
"我设置了 cors 原点:'*'" — 怎么样?在哪里?
-
这是一个 400 bad request 错误并返回 { message: "Sorry, bad request" }
标签: javascript ajax api axios fetch