【问题标题】:GET/POST in axios not working but fetch worksaxios 中的 GET/POST 不工作,但 fetch 工作
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2014-06-23
    • 2022-01-24
    • 2019-07-18
    • 2022-01-08
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多