AWS API call is being blocked by the CORS policy - reactjs

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

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

tried to access the data via axios but Response to preflight request doesn't pass access control check

I was working over react and made a request using axios but in the browser it shows "Response to preflight request doesn't pass access control check" i had installed the corx extension but still getting the same error
Assuming you are using create-react-app you can try defining a proxy property in your package.json file and give the url to your api server, something like
"proxy": "http://localhost:8000".
This will proxy your api calls through the express server provided within create-react-app without the need for any CORS configuration in your browser
Note : This can be only used in your local environment and for production setup, you should try alternate approaches by configuring CORS setting in the API server or hosting the UI and API applications under the same hostname

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.

Access control allow origin with ReactJS sample web app

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

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

Resources