【问题标题】:Getting data from metaweather API to react page从 metaweather API 获取数据以响应页面
【发布时间】:2021-06-24 14:32:14
【问题描述】:

我尝试使用这个 metaweather API,但它不起作用。这是一个反应项目,我正在使用本地主机。 plz,谁能告诉我我在这里做错了什么?

const fetchWeatherData = async() =>{
   fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
    method:'GET',
    mode:'no-cors',
    headers: {
      'Content-Type': 'application/json',
    },
    
})
  .then(response => {
    console.log('response',response);
return response.json();
  })
  .then(data => {
    console.log('data',data);
  })
  .catch((err) => {
    console.log(err)
})}

这些是我得到的日志

【问题讨论】:

    标签: javascript reactjs fetch


    【解决方案1】:

    你只是没有用大括号关闭函数,我测试了它,它工作正常,只需调用函数fetchWeatherData

    const fetchWeatherData = async() => {
        fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
         method:'GET',
         mode:'no-cors',
         headers: {
           'Content-Type': 'application/json',
         },
         
     })
       .then(response => {
     return response.json();
       })
       .then(data => {
         console.log('data',data);
       })
       .catch((err) => {
         console.log(err)
        })
    }
    
    fetchWeatherData()

    【讨论】:

    • 很抱歉缺少大括号,但我尝试了你的代码。相同的结果@Aian
    • SyntaxError: Unexpected end of input and response.status = 0 @Aian
    • aa ,你应该在服务器端调用它,因为 MetaWeather API 不支持 CORS,请检查这个stackoverflow.com/questions/58147524/…
    • 如果在服务器端调用此代码将正常工作
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多