Roberto Chirila
Roberto Chirila

Reputation: 125

Problem returning json when using fetch in React app

Guys I am developing a simple weather application using openweatherapp API and React. I am trying to fetch the data in componentDidMount and parse it as JSON. However instead of receiving the JSON, I am receiving the HTML page. When I am trying to hit the API from the browser though, the correct JSON is returned.

I would really appreciate some help, I will post my code below.

import React, { Component } from "react";
import { CurrentWeatherForecast } from "./components/CurrentWeatherForecast";
import { NextDaysWeatherForecast } from "./components/NextDaysWeatherForecast";

export class App extends Component {
componentDidMount() {
    console.log("it mounted");
    fetch(
        "api.openweathermap.org/data/2.5/weather?q=London&appid=1fc71092a81b329e8ce0e1ae88ef0fb7"
    )
        .then((res) => res.text())// this returns the page, if I change to res.json() I receive an error
        .then((data) => {
            console.log("Success:", data);
        })
        .catch((error) => {
            console.error("Error:", error);
        });
}
render() {
    return (
        <div>
            <CurrentWeatherForecast />
            <NextDaysWeatherForecast />
        </div>
    );
}
}

export default App;

Upvotes: 0

Views: 70

Answers (1)

Bobby Graczyk
Bobby Graczyk

Reputation: 86

Add 'https://' to your query URL. Server is returning a 404 page.

Upvotes: 4

Related Questions