提取错误否'访问控制允许来源'标头出现在请求的资源上 [英] fetch error No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:64
本文介绍了提取错误否'访问控制允许来源'标头出现在请求的资源上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用访存API从其他API获取数据,这是我的代码:

I'm using fetch API to get data from other APIs this is my code:

var result = fetch(ip, {
        method: 'get',
    }).then(response => response.json())
      .then(data => {
        country = data.country_name;
        let lat = data.latitude;
        let lon = data.longitude;                       
        //fetch weather api with the user country
        return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`);
    })
    .then(response => response.json())
    .then(data => {
        // access the data of the weather api
        console.log(JSON.stringify(data))
    })
    .catch(error => console.log('Request failed', error));

但是我在控制台中遇到错误:

but I face error in console:

Fetch API cannot load https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/52.3824,4.8995. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我为第二次提取设置了标头:

I set headers for the second fetch:

return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
  mode: 'no-cors',
  header: {
    'Access-Control-Allow-Origin':'*',
  }
}); 

错误将消失,但 console.log(JSON.stringify(data))不会在控制台中记录任何内容,并且提取操作不会返回任何值.我的代码有什么问题?

error will gone but console.log(JSON.stringify(data)) do not log anything in console and the fetch not return any value. what is the problem with my code?

推荐答案

问题不在您的JavaScript代码中,而是在API中,如果您是此API的所有者,则服务器不支持跨源请求您必须在响应中添加'Access-Control-Allow-Origin'标头,并标明允许的来源(*表示允许来自任何来源).在某些情况下, jsonp 请求可能有效.

The problem is not in your JavaScript code, it is in the API, the server doesn't support cross origin request, if you are the owner of this API you have to add 'Access-Control-Allow-Origin' header to the response with the allowed origins (* to allow from any origin). in some cases jsonp request may work.

注意:仅当从浏览器生成请求时,才会发生此问题

Note: this problem happen only when the request is generated from the browser

这篇关于提取错误否'访问控制允许来源'标头出现在请求的资源上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆