首页 文章

使用api时访问控制允许来源

提问于
浏览
0

一直在寻找解决这个问题的方法:

Fetch API无法加载https://api.wunderground.com/api/ ****** / conditions / q / toronto . 'Access-Control-Allow-Origin'标头具有值_137204_ ' that is not equal to the supplied origin. Origin ' http://localhost:3000 ' is therefore not allowed access. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request' s模式到'no-cors'以获取禁用CORS的资源 .

const apiKey = '******'
const apiUrl = 'https://api.wunderground.com/api/' + apiKey + '/conditions/q/'

var WeatherApi = {
  get: function(query) {
    return fetch(apiUrl + query).then(function(response) {
      return response.json();
    });
  }
};

  handleClick: function() {
    WeatherApi.get(this.state.text).then(function(data) {
      console.log(data);
    }.bind(this));
  },

那么如何让服务器发送带有效值的标头?

1 回答

  • 0

    这些“CORS”请求依赖于浏览器发送到服务器的OPTIONS谓词以及允许跨源请求的服务器 . 虽然,根据API,您可以通过CORS限制,请记住浏览器正在抱怨,如果您可以使用相同的呼叫服务器端,则不会出现问题(至少在浏览器级别,API可能仍然需要某些 Headers ) .

    如果您必须从浏览器执行此操作,那么您必须遵循消费API必须支持以允许访问的严格准则 . 下面的RFC描述了整个OPTIONS动词协议(在RFC中称为pre-flight),你总是可以在Chrome开发中看到它们 . 工具并使用它们来调试问题 .

    很可能你的API期待一些你不提供的令牌或者dev . (localhost问题)头 .

    这是RFC链接 . 第5.x节是你想要的宝石,所以请确保你阅读了本节的所有内容......

    https://www.w3.org/TR/cors/#syntax

    希望能帮助到你

    编辑1

    在本地开发框中,在IIS或apache中,确保提供“响应标头”

    Access-Control-Allow-Origin ---> "https://api.wunderground.com"
    

相关问题