【问题标题】:Problem using fetch to retrive data from an API - works in Postman使用 fetch 从 API 检索数据的问题 - 在 Postman 中工作
【发布时间】:2021-09-30 07:57:23
【问题描述】:

我正在尝试使用 JavaScript 访问 API。使用 Postman 访问它时,一切正常。我可以发出 GET 请求,它会发回正确的数据。但是,当我尝试使用 fetch() 执行相同操作时,它要么不返回任何内容,要么给我一个错误(取决于我使用的模式)。

<script>
    async function get_page() {
        const response = await fetch("MY_LINK", {
            method:'GET',
            mode:'cors',
            redirect:'follow'
            });
            return response;
        }
    get_page().then(data => console.log(data)).catch(err => console.log(err));
</script>

以上抛出:

从源“null”到“MY_LINK”获取的访问权限已被阻止 CORS 策略:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。如果不透明的响应满足您的需求,请将 请求模式为“no-cors”以获取禁用 CORS 的资源。

如果我将模式更改为no-cors,我会收到回复,但似乎无法在其中找到返回的消息(body 属性为空),这是我在使用 Postman 时看到的。

【问题讨论】:

  • 在邮递员中工作,但在浏览器中不工作 - 是的,你是对的,因为这就是 CORS 的工作方式 - 服务器需要允许浏览器访问响应 - 更改 服务器 这样做 - 至于 no-cors,您现在知道什么是不透明响应......即看不到任何信息
  • @Bravo Postman 怎么可能仍然能够给出正确的响应(只是想知道)?
  • 我认为这个主题回答了你的问题:stackoverflow.com/questions/36250615/cors-with-postman
  • 因为 POSTMAN 不是浏览器

标签: javascript fetch


【解决方案1】:

在浏览器中,使用您的功能,这有效:

get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));

完整代码(戳 api :)

async function get_page() {
        const response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto', {
            method:'GET',
            mode:'cors',
            redirect:'follow'
            });
            return response;
}
        
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));

关于 CORS 的注意事项:

访问时在浏览器控制台上测试:

所以看看你的服务器代码也是值得的

这是我的代码的结果:

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2022-01-20
    • 1970-01-01
    • 2019-08-08
    • 2016-12-25
    • 2020-06-29
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多