1
votes

I have been trying to use the following code using React fetch to get a response from the OpenWeather API:

    fetch('api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890')
    .then(response => response.text())
    .then(data => {
       console.log(data)

When I skip react and just copy the url (api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890) into the browser I get a totally valid response. (For example ) When I use the fetch code in my React application, however, I get the following error:

Request URL: http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890
Request Method: GET
Status Code: 431 Request Header Fields Too Large
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade

I am running my react application off localhost from create-react-app. Why can I access that API just fine from my browser but get an error in my app?


Extra Information

In case it is useful here is the link to sign up for a free OpenWeather API

Here is the rest of the information from the response header:

HTTP/1.1 431 Request Header Fields Too Large
x-powered-by: Express
connection: close
date: Wed, 18 Sep 2019 15:45:21 GMT
transfer-encoding: chunked

Or from the request header:

GET /api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Accept: */*
Sec-Fetch-Site: same-origin
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es-US;q=0.8,es;q=0.7,ar-JO;q=0.6,ar;q=0.5

(My APPID is fake in all these examples, so the request won't work by just copying and pasting what I have)

1
What are you sending in your "headers"? - zhuber
I guess I'm not totally sure. I am either using the fetch above (1st code block) or just copying the URL. My best guess at to what I'm sending for request headers is what I have copied in that last code block above. I got that from the developer console under Network. - Rachel W

1 Answers

1
votes

It's a pretty "catchy" bug - you are missing http:// in front of your url, so:

fetch('https://api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890')

Since you've missed it, url is resolved to this (you can see it in your Network tab):

http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Milwaukee&APPID=1234567890