【问题标题】:TypeError Failed to fetch when doing GET requestTypeError 执行 GET 请求时获取失败
【发布时间】:2022-11-21 15:18:48
【问题描述】:

我有一个在 node.js 中创建的端点,它获取并返回一些数据。

我想在我的反应前端中获取这些数据。

这是我在后端的内容:

app.get('/retrieveQuestion', (req, res) => {
    axios.get("https://data.mongodb-api.com/app/data-pkrpq/endpoint/getEasyChallenge",{
        headers: {
            'api-key': process.env.APIKEY
        }
    }).then((resp) =>{
        res.send({ challenge: resp.data })
    })
});

当我尝试在此端点上执行 GET 请求时,我得到了我期望的数据。

当我尝试在我的前端GET这个数据时:

function getEasyQuestion(){
    axios.defaults.headers["Access-Control-Allow-Origin"] = "*"
    axios.get("http://localhost:5000/retrieveQuestion")
    .then((res) =>{
        console.log('res',res)
    })
}

我收到错误:

GET http://localhost:5000/retrieveQuestion net::ERR_FAILED 200
Uncaught (in promise) TypeError: Failed to fetch
    at getEasyQuestion (Editor.js:72:1)

我注意到我在上述错误之前收到此错误:

Access to XMLHttpRequest at 'http://localhost:5000/retrieveQuestion' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

【问题讨论】:

  • 是后端Mongo请求出错,还是FE实际接收出错?您能否在 BE 上打印 resp.data 并按预期检查它是否存在。您是否在请求网址中检查过 httpshttp 之类的内容?如果你谷歌它有一大堆潜在的错误原因,必须缩小范围。
  • @Jayce444 后端按预期打印数据。我可以使用完全相同的 URL GET 来自邮递员的数据,它在本地运行所以 http
  • 再次@Emm,如果没有更多信息,我们可能会遗漏潜在原因。您是否正在使用 cors 中间件,例如app.use(cors());?您是否检查过后端发送的响应内容类型标头与浏览器期望的内容类型标头是否相同,即 JSON?您是否尝试过 Express JSON 方法?即res.json({ challenge: resp.data })
  • @Jayce444 不确定它是否有帮助,但也包含在问题中,这个错误似乎是其他一切的根本原因:Access to XMLHttpRequest at 'http://localhost:5000/retrieveQuestion' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

标签: javascript node.js reactjs axios


【解决方案1】:

我想你正试图从访问数据http网址到https(安全)页面。这是不允许的。

尝试托管此网站,或者您可以使用ngrok之类的临时服务

使用npm i ngrok

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 2021-10-01
    • 1970-01-01
    • 2021-11-05
    • 2013-01-15
    • 2018-02-20
    • 2017-03-10
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多