Access control allow origin with ReactJS sample web app - reactjs

I am facing problem with the following CORS issue when I run my ReactJS sample web app in Chrome browser.
Access to XMLHttpRequest at 'https://XXXX.XXX/YYY/ZZZ/' from origin 'http://localhost:3003' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I read the solution and installed CORS Chrome plugin. I added REST URL in CORS settings as shown in below screenshot. I cleared Chrome browser history and try running ReactJS web app, but still it is throwing the same error. Can someone guide how to exactly fix this? I also tried
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
in code, but not fixed this issue.

You can try a workaround with https://cors-anywhere.herokuapp.com
Have a look at my solution in here: https://stackoverflow.com/a/52986448/5692089

Related

Cannot fetch from API inside docker container from react app due to 'Access-Control-Allow-Origin'

I am running azure functions API inside a docker container and I can access it without problem from postman or e.g. chrome, but I fail to access it from react app. I get an error:
from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
If I run API locally not in the container I can use local.settings.json with:
"Host": {
"LocalHttpPort": 7071,
"CORS": "*",
"CORSCredentials": false
}
if I host API in the cloud I can configure CORS in it, but what about when running it in the docker container?
I've been reading different post trying to figure this out but I still fail to find an answer, or an answer that I can understand :/
Is there something I can modify like local.settings.json or similar? or do I need to modify Dockerfileor something else?
CORS is a browser protection which require an extra header to be resolved . It is a protocol which work between api and browser thus docker can't do anything
So you can change either change your api to send the correct headers explained below .
CORS in Docker Engine REST Api - DevOps Stack Exchange
Here we will be directly sending the Access-Control-Allow-Origin header with the it's value set as '*' this will tell the browser to use the same origin resource .
A different approach would be the use of using nginx as a proxy with docker
explained below . Here the proxy will change the header .Here you don't have to change your api .
Solving CORS problem on local development with Docker | by Maximillian Xavier | Medium

AWS API call is being blocked by the CORS policy

I created a DynamoDB table and attached 3 lambda functions to it. I'm trying to call these functions by attaching an API Gateway trigger to them. I created a Rest API and then the get method. Afterwards, I deployed the API and the API link works as intended. I'm now trying to call the API using a Axios in React.
axios.get("Link")
.then(res => {
console.log(res);
})
The problem is that whenever I try to run this on a local server, I get the following error.
Access to XMLHttpRequest from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried enabling CORS on the API Gateway but that doesn't work either. I know the problem lies somewhere in the backend but I can't figure out what I'm supposed to do.
If you have enabled CORS then this is expected behaviour. CORS will not allow other domains to access your API unless otherwise configured.
Check how to properly configure CORS on API-Gateway from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
For your development / test / learning environment you can disable* CORS and then you can call API from localhost.
More troubleshooting on API Gateway CORS issue:
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cors-errors/
*It is not recommended based on security grounds
Try opening chrome with CORS security disabled.
Mac OS:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security

CORS issue React Axios

I am trying to get a login screen to work on React, still new to this stuff. I have finally gotten requests to at least partially work, but now I am getting this error
Access to XMLHttpRequest at 'http://localhost:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I read a few articles and came across this one https://medium.com/#dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9
Which says to use this code
Access-Control-Allow-Origin: http://localhost:3000
But I am not sure exactly where this line of code should go.
I believe this needs to be fixed on the API. I'm not sure what you're hosting on your API on, but if it's express, then doing something like:
const cors = require('cors');
app.use(cors());
Alternatively, for testing purposes, you can install cors plugins on chrome and firefox.

CORS request did not succeed - react

I make this API request , using axios in ReactJS
axios.post(`${API_URL}/valida_proximo`, {
id: images.map(image => image.id)
},
getAxiosConfig())
// this.setState({ images, loadingAtribuiImagens: false})
}
It works really well in Google Chrome, but on Firefox I receive an error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/valida_proximo. (Reason: CORS request did not succeed).[Learn More]
What can I do?
This is my API
#blueprint.route('', methods=['POST', ])
#jwt_required()
def index():
if request.json:
id_usuarioImagem = request.json.get('id')
imagens_selecionadas =
UsuarioImagem.query.filter(UsuarioImagem.id.in_(id_usuarioImagem)).all()
if imagens_selecionadas:
for imagem_selecionada in imagens_selecionadas:
imagem_selecionada.batido=True
db.session.commit()
return 'ok', 200
return 'error', 400
CORS errors are usually associated with cross domain requests and something not configured to accept a request on the recipient side of the request. The fact that chrome is working but firefox doesn't seems rather strange.
This was a method I used:
Open Firefox browser and load the page.
Perform the operation which is throwing Cross Origin Request Security (CORS) error.
Open firebug and copy the URL which is throwing Cross Origin Request Security (CORS) error.
Load the same URL in another tab in same Firefox browser.
Once you open the URL in another tab will ask you to add the certificate.
After adding the certificate will resolve Cross Origin Request Security (CORS) error and now you will not be getting this error.
I'm not too familiar with Axios, but it looks like you're making a post request from your React to your Flask backend. If the front-end and the backend are on different ports (like your Flask seems to be on PORT 5000), then you're making a CORS request.
With CORS, depending on what you're posting, you might need to include some Access-Control headers in your Flask response object. You can do this either manually, or just pip-installing and using the 'flask-cors' package. Import the package into your app factory and use it like so (see their docuementation for more info):
from flask_cors import CORS
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
CORS(app)
The request might also get 'preflighted' with an 'OPTIONS' request, also depending on the nature of your POST. More information would be helpful
This is a bug in firefox.
if you follow the link (MDN) in the error msg . you will find:
What went wrong?
The HTTP request which makes use of CORS failed because the HTTP connection failed at either the network or protocol level. The error is not directly related to CORS, but is a fundamental network error of some kind.
which i read as the connection failed and not a problem with CORS settings.
you will just have to ignore the error message until firefox gets it fixed.
The error has something to do with refreshing the page and long polling requests or service workers and polling requests.
If anyone sees this question again, I had this problem because I made a request to https://url instead of http://url

GET request throws error after app implemented SSL: Mixed Content: This request has been blocked; the content must be served over HTTPS"

Mixed Content: The page at 'https://www.example.com/dashboard' was
loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://api.example.com/inventory/10/'. This request has been blocked;
the content must be served over HTTPS.
We have this Angular web app that runs with Flask on the back-end.
Everything was working fine until we implemented SSL. Afterwards, we keep getting this strange error everywhere.
Now, the $http.get request in my dashboard.js is definitely calling "https://api.example.com/inventory/10" in the code below and yet the error is claiming that we are trying to request "http" instead.
$http.get($rootScope.baseUrl+'/inventory/' + item.id)
where rootScope.baseUrl is "https://api.example.com".
It's really weird because some GET requests ARE going through from our web application to our back-end, but some requests are throwing this weird error.
Here's the header that gets an error in our Network tab of the console in chrome.
Request URL:https://api.example.com/inventory/10 Request Headers
Provisional headers are shown Accept:application/json, text/plain, /
Origin:https://www.example.com
Referer:https://www.example.com/dashboard
It was a weird case that came down to removing a forward slash from the end of a URL fixing everything. Somehow, whenever we made a GET request using $http in Angular like baseurl + inventory.id + "/", it would make a http request but as soon as remove that slash, it would make the https request correctly.
Still so confused
I think the root of the problem is in server redirects. I was able to resolve same issue with SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') setting for Django (its running behind AWS balancer). Here is documentation.

Resources