OpenWeather API React Request Header Fields Too Large 431 - reactjs

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)

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

Related

Unable to upload an empty file in google cloud when doing resumable upload in ReactJS . it's showing CORS Error

Below is My Request Header , access-control-allow-origin is already set to * in Request Header as shown below but still CORS Error is coming (it's coming only when trying to upload a empty file)
:authority: storage.googleapis.com
:method: PUT
:path: /sms-local-bucket/3f9e2365-8d03-40e2-9635-a3d1860a7f23/8a70f7a3-59ff-4d36-b0ce-8e32efe55493?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=sfs-local%40revbits-sfs-local.iam.gserviceaccount.com%2F20211029%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20211029T034429Z&X-Goog-Expires=61&X-Goog-SignedHeaders=content-type%3Bhost%3Bx-goog-resumable&X-Goog-Signature=0def04860fcda4d9c316544eef3482491e4f70cd4f9e397fe282b03a728b9f91465f3669f616e5e6fde72a765ca872624ed3d2ff60f5fa3735cabc03d640e409e2240a58229e23ee882e37998c038ca1c9b8e47dbc38765a9056b2c14268bcbf6595d21a9056b5df1b8808a5fde0d83b9b2d815482a073c8ca7662c872aa01a6884baea466cacf05c2b39c09ab1d0b7838b31f7c96d7f4c470fcff4cc753d5cc00122077d1cbbfb40ce715644a6c85a53c68349b8d7831a31cd3f8006840658a9516209d1f128d84c34961597ec148992caf5e3b4e141144632bd2a5b82528d127a3816840ebb063de8376ee1fc9c3a70894057e9adab9ff58b7de4e99d23f09&upload_id=ADPycdtHTqXlDLRx1GxLY6W3FsJHuxT0VJJNqtdPpQ3DxlfS8TvCeTjOFhDSTQCsrb2VMGgnAER1CPNOStNV2Uus4WSTJpzsGQ
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en-US;q=0.9,en;q=0.8
access-control-allow-origin: *
content-length: 0
content-range: bytes 0--1/0
content-type: application/octet-stream
origin: http://localhost:3000
referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
x-client-data: CJG2yQEIorbJAQipncoBCO/yywEInvnLAQjnhMwBCPqEzAEItYXMAQjLicwB
Decoded:
message ClientVariations {
// Active client experiment variation IDs.
repeated int32 variation_id = [3300113, 3300130, 3313321, 3340655, 3341470, 3342951, 3342970, 3343029, 3343563];
}
If you create the application in localhost header('Access-Control-Allow-Origin: *'); and if it is not working, install the CORS Everywhere plugin in your browser and then check the response and it will work fine.
Plugin URL :
For Firefox : https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/
For Chrome : https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
Also, Chrome does not support localhost for CORS requests (an error opened since 2010) [1], if you inspect the thread of this error.
For more information on CORS, please refer to the following document[2].
[1] https://bugs.chromium.org/p/chromium/issues/detail?id=67743
[2] https://cloud.google.com/storage/docs/xml-api/put-bucket-cors

CORS fails to work once I add a JWT authorization header

I have a Flask backend and a React front-end. The Flask backend is an API that will communicate with other microservices. In development I have my React front-end running on localhost:3000 and the Flask app running on localhost:5000.
Clearly these are different ports which will throw a CORS error by default. So I added Flask_CORS and allowed traffic from localhost:3000. This works and I can now serve GET and POST requests.
I then add my Firebase authentication to the front-end. I receive a JWT and then I want to send the JWT with ech API request to ensure that the user is allowed to make certain requests, which will be validated on the Flask backend.
I added the token_id to the headers in the Axios request to my back-end, but now I am getting the following error:
localhost/:1 Access to XMLHttpRequest at 'http://localhost:5000/items' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
When I examine the network tab I notice that without the JWT the request passes through fine. See below for header content:
General:
Request URL: http://localhost:5000/items
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:5000
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: http://localhost:3000 <--This line is my concern
Content-Length: 37
Content-Type: application/json
Date: Fri, 06 Sep 2019 09:10:10 GMT
Server: Werkzeug/0.15.5 Python/3.7.4
Vary: Origin
Request Headers:
Provisional headers are shown
Accept: application/json, text/plain, /
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
I then only add the JWT to the Authorization header config of an Axios interceptor and now the request fails with the following headers present in the Network tab:
General:
Request URL: http://localhost:5000/items
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 127.0.0.1:5000
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Allow: POST, OPTIONS, HEAD, GET
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Fri, 06 Sep 2019 09:14:46 GMT
Server: Werkzeug/0.15.5 Python/3.7.4
Request Headers:
Provisional headers are shown
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Mode: no-cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
I noticed that the Access-Control-Allow-Origin disappears when the Authorization header is added and instead an Access-Control_Request-Headers is present.
The code of interest in the front end is below
import axios from 'axios';
import * as firebase from "firebase/app";
import 'firebase/auth';
const instance = axios.create({
baseURL: 'http://localhost:5000/',
});
instance.interceptors.request.use(config => {
const id_token = firebase.auth().currentUser.getIdToken();
config.headers = { Authorization: id_token}; <---Commenting out this line works
return config
}, error => {
return Promise.reject(error);
})
export default instance;
I do not know how or why the CORS fails to work as soon as a JWT is added. I suspect it is because once the JWT is added there is a pre-flight request. But I have changed nothing on the server side so I am puzzled as to why the server would not provide a suitablelCORS response just because a JWT is added.
Any pointers would be appreciated.
You can define CORS at the top of the main file, it will allow all the CORS requests
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
#app.route("/api/test")
def test_cors():
return "CORS allowed"

CORS 'Access-Control-Allow-Origin' header not present issue

I'm writing the client-side of an app with ReactJS, I'm stuck at getting data from a certain api. I get "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access" error.
As I suppose the server is missing the "Access-Control-Allow-Origin" headers in order to enable CORS but what I don't understand is why when I'm trying to make an AJAX call with "Restlet Client - REST API testing" browser extension it actually works. I get a following success response. But It doesn't work inside my actual React Request. Is there a way I can to get rid of this error without any changes on the server side? Why does this extension actually work?
Connection: keep-alive
Content-Type: application/json; charset=UTF-8;
Date:
2017 Sep 22 22:45:40-1m 50s
Server: ..../1.6.2
Transfer-Encoding: chunked
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
My React code but nothing special in there, just testing if I'm getting a response
componentWillMount() {
const url = "https://myserver.ru/api/issue?perPage=10";
Request.get(url).then((response) => {
this.setState({
issues: response
});
});
}
If you are making a cross-site requests then browser will expect Access-Control-Allow-Origin headers from the server. The value of that header can be,
Access-Control-Allow-Origin: *
or
Access-Control-Allow-Origin: http://localhost:3000
When you are requesting from localhost, make sure it also need to add port number as well.
More about CORS documentation:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Hope it helps.

Breeze always 404

I built a oData-Service which works well.
Now I want to query them with Breeze but I always get an 404 error.
In Fiddler I see first a 200 with empty Body and then follows the 404 with "No HTTP resource was found that matches the request URI".
But running in a normal browser the odata Service delivers the right data.
I debug it and set a breakpoint on the Server to see if the service is called correctly. After sending the request the breakpoint shows that the Service is called. But parallel to the break breeze calls the fail-method of
manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
and e.message is empty.
Any idea??? :-/
Next entry...
I deactivate CORS and now I get the 404 immediately.
Here is the request:
OPTIONS xxx:8080/myDataService/odata/Person?$select=Name HTTP/1.1
Host: xxx:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin:localhost:61244
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36
Access-Control-Request-Headers: dataserviceversion, accept
Accept: /
Referer: http://localhost:61244/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
and here the answer:
HTTP/1.1 404 Not Found
Content-Length: 178
Content-Type: application/json; odata.metadata=minimal
Server: Microsoft-HTTPAPI/2.0
OData-Version: 4.0
Date: Mon, 19 Jan 2015 12:11:48 GMT
{
"error":{
"code":"","message":"No HTTP resource was found that matches the request URI xxx:8080/myDataService/odata/Person?$select=Name'."
}
}
No surprise that the OPTION request passes; you've probably got the server set to say "OK" to every request ... and that's just fine for now.
The rejection has to do with the address of your GET request: xxx:8080/myDataService/odata/Person. Are you sure that's the right endpoint? The path is usually plural (Persons).
It's easy enough to just paste that url into a browser address bar and see what it does.

Structr CORS api request

I'm trying to make a XHR request from my AngularJS instance running on port :8080 to my Structr instance running on port :8082
Thing is, Structr doesn't seem to accept OPTIONS requests on port:8080
Here is the Request header :
OPTIONS /structr/rest/issues HTTP/1.1
Host: localhost:8082
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: GET
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
Access-Control-Request-Headers: accept, -hx-password, -hx-user
Accept: */*
Referer: http://localhost:8080/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,nl;q=0.2
Here is the Response headers from the server:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST
Access-Control-Allow-Origin:http://localhost:8080
Content-Length:44
Content-Type:application/json; charset=utf-8
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Server:Jetty(9.1.4.v20140401)
Set-Cookie:JSESSIONID=1w7n8c71lcbh31s7kwygtat69c;Path=/
The most interesting part IMHO is
Access-Control-Allow-Methods:GET,PUT,POST
I have to say that my understanding of java and HTTP Requests is really sparse so I don't really feel like digging in the source code...
Or maybe it's a simple Angular thing everyone knows but me...
Thanks to Axel Morgner the answer is :
There are two ways to solve it:
1: Let Structr serve also the AngularJS code.
2: Configure the REST > endpoint to accept OPTIONS using a ResourceAccess flag, see docs.structr.org/rest-user-guide#Securing > REST Endpoints.
Beware that when you create a Schema, structr automatically creates new resourceAccess nodes for the new possibles actions.

Resources