【问题标题】:Fetch call works in Postman but not localhost:3000Fetch 调用在 Postman 中有效,但在 localhost:3000 中无效
【发布时间】:2021-11-02 11:26:24
【问题描述】:

我可以使用 Postman 从 Fruityvice 获取此 API。但是当我在本地运行它时,我遇到了 CORS 问题。

我一直在引用 Attempted SolutionAttemped Solution 2 来尝试清除错误,但没有成功。

任何指针以及我哪里出错了?谢谢!

初始提取调用

const fetchFruitInformation = async() => {

  const response = await fetch("https://www.fruityvice.com/api/fruit/all");
  if (!response.ok) {
    throw new Error(response.statusText);
  }

  return response.json();
};
这给了我一个CORS错误

错误

CORS 策略阻止了从源“http://localhost:3000”获取“https://www.fruityvice.com/api/fruit/all”的访问权限:否“Access-Control-Allow-” Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

然后我添加{mode: 'no-cors'}{mode: 'cors}

更新的 Fetch 调用

const fetchFruitInformation = async() => {

  const response = await fetch("https://www.fruityvice.com/api/fruit/all", {
    mode: 'no-cors'
  });

  if (!response.ok) {
    throw new Error(response.statusText);
  }

  return response.json();
};

会引发错误

apiCalls.js:7 Uncaught (in promise) 错误 在 fetchFruitInformation (apiCalls.js:7)

【问题讨论】:

标签: javascript reactjs cors


【解决方案1】:

https://www.fruityvice.com/api/ 不会在请求的响应中发送 Access-Control-Allow-Origin: * 标头,因此浏览器会抱怨 CORS 问题,而 Postman 不会。一种解决方案是将所有相关请求代理到后端的https://www.fruityvice.com/api

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2020-04-06
    • 1970-01-01
    • 2014-05-13
    • 2018-02-21
    • 2020-04-28
    • 2023-03-22
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多