0

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;
6
  • 1
    this returns the page, if I change to res.json() I receive an error - because the result is NOT json? oh, wait ... it is JSON ... what text exactly does it return Commented Sep 16, 2020 at 12:20
  • did you set the header? Commented Sep 16, 2020 at 12:20
  • @jaromandaX the result is json because I can see it returned in the browser if I am using that link. Commented Sep 16, 2020 at 12:22
  • What is the error? Commented Sep 16, 2020 at 12:22
  • 2
    @RobertoChirila - external (to your site) links need to start with http:// or https:// or at least // Commented Sep 16, 2020 at 12:27

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

i.e. it's trying to fetch http://your server/api.openweathermap.org/data/2.5/weather?q=London&appid=1fc71092a81b329e8ce0e1ae88ef0fb7
@RobertoChirila - thing is, you should check in the browser dev console the response - then you wouldn't have said that it DOES return JSON - when clearly the response was YOUR SERVERS 404 page :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.