【问题标题】:Not able to fetch get request from 5 day weather forecast API of OpenWeather website using axios in React无法使用 React 中的 axios 从 OpenWeather 网站的 5 天天气预报 API 获取获取请求
【发布时间】:2021-07-07 21:10:29
【问题描述】:

您好,我是 React 的初学者,正在开发一个非常简单的天气网站,该网站显示特定城市的 5 天预报。 最初我建立了一个没有数据的简单的前端。现在我打算使用 OpenWeather 网站提供的 API 填写数据 Here is the link

我正在使用 axios 在 react 中获取 get 请求 但是当控制台记录响应时,我的代码无法获得响应,它显示错误 404 它显示此错误

xhr.js:177 GET http://localhost:3000/api.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b606f9db39d148829c9500a2651c63dd 404 (Not Found)

createError.js:16 Uncaught (in promise) Error: Request failed with status code 404

    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

这是我的代码

App.js

import React from 'react'

import Navbar from './Components/Navbar/Navbar'
import Cities from './Components/Cities/Cities'

const App = () => {
  return (
    <div>
     
      <Navbar/>
      <h1>City Name</h1>
      <Cities/>
    </div>
  )
}

export default App

城市.js

import React from 'react'

import Day3 from './City/Day3'
import Day1 from './City/Day1'
import Day2 from './City/Day2'
import Day4 from './City/Day4'
import classes from './Cities.module.css'


const Cities = () => {

    return (
        <div className={classes.Cities}>
           
            <Day1/>
            <Day2/>
            <Day3/>
            <Day4/>
        </div>
    )
}

export default Cities

Day1.js

import React, { Component } from 'react'
import { WiDayCloudy } from "weather-icons-react"
import classes from './City.module.css'
import axios from 'axios'
class Day1 extends Component  {

    componentDidMount(){
        axios.get('api.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b606f9db39d148829c9500a2651c63dd').then(
            response=>{
                console.log(response)
            }
        )
    }

    render(){
        return (
        <div className={classes.City}>
         <WiDayCloudy size={100} color='rgb(156, 231, 231)' />
           <h1>Day 1</h1>
           <h4>Maximum temperature</h4>
           <h4>Minimum Temperature</h4>
           <h4>Humidity</h4>
           <h4>Precipitation</h4>
        </div>
    )

    }
    
}

export default Day1

第 2 天 第 3 天 第 4 天与第 1 天相同

请帮忙

【问题讨论】:

  • 尝试在你的url前加https://,否则axios认为url是你当前域的路径

标签: reactjs


【解决方案1】:

你的问题来了

"http://localhost:3000/api.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&amp;appid=b606f9db39d148829c9500a2651c63dd"

应该是这样的:

"https://api.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&amp;appid=b606f9db39d148829c9500a2651c63dd"

为此获取请求配置您的 axios

【讨论】:

    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2012-11-01
    相关资源
    最近更新 更多