CORS issue React Axios - reactjs

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.

Related

CORS Not Working - No Access-Control-Allow-Origin' header

thank you for taking a look at my question. I have been building my flask app to help deliver some calculatoins in python to my React front end. I am attempting to bridge the gap between the two different servers but am having trouble with CORS (from the looks of it along with many others new to flask with react)
I have tried to change around many things like adding #cross_origin, origins: '', and headers.add("Access-Control-Allow-Origin", "") but no success. All I need from flask is the result of my functions. Has anyone else run into an issue similar or know a way I can fix this?
Flask Code:
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*", "allow_headers": "*", "expose_headers": "*"}})`
#app.route('/')
#cross_origin()
def welcome():
response = jsonify({'reply': 'Hello Webminers'})
response.headers.add("Access-Control-Allow-Origin", "*")
return response
React Code:
console.log(axios.get('http://127.0.0.1:5000'))
Console:
Access to XMLHttpRequest at 'http://127.0.0.1:5000/' from origin 'http://localhost:3000' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Failed to load resource: net::ERR_FAILED
P.S not sure if this matters or not but I have also gotten the same response with 'localhost:5000 from origin localhost:3000'
Edit:
axios.get('http://127.0.0.1:5000', {headers: {"Access-Control-Allow-
Origin": "*"}}).then(response => {
console.log(response.data);
})
I added this in and got this new response from the console
Access to XMLHttpRequest at 'http://127.0.0.1:5000/' 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
I believe that I found the issue. I was looking around and trying a bunch of different things and even attempted to recreate the API in fastAPI to reach the same results.
However, I have just found this comment stating that they had an issue where React would be running but leaving the API behind thus causing errors for not being able to get the data from my API. https://stackoverflow.com/a/58786845/19683392
I am currently still looking for the solution and may open a new question but for now, I am getting this error:
TypeError: NetworkError when attempting to fetch resource.
More updates soon...
*** Edit ***
FOUND IT!
Bam fixed it with the concurrent library's help
"start": "concurrently \"react-scripts start\"
\"flask --app Backend/FlaskAPI.py run\"",
Is the config I used for anyone else who runs into the same issue
You don't need to manually set the header, the CORS package will handle that for you. Also in frontend you don't need to specify CORS header when calling the API
Can you try the following way?
app = Flask(__name__)
CORS(app)
#app.route('/')
#cross_origin()
def welcome():
response = jsonify({'reply': 'Hello Webminers'})
return response
Then access the api like this:
axios.get('http://127.0.0.1:5000').then(response => {
console.log(response.data);
})

Sanity io No 'Access-Control-Allow-Origin

[enter image description here][1]I am having trouble getting my Sanity io posts to render. This is the error I am getting this error.
post:1
Access to XMLHttpRequest at 'https://wuj77i1.api.sanity.io/v1/data/query/production?query=*' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
browser-request.js:117
GET https://wuj77i1.api.sanity.io/v1/data/query/production?query=*\ net::ERR_FAILED 403
Can you recommend any solutions to overriding the CORS Origin?
I have added the localhost of my React Project to allow credentials but I am still getting this error.
Images of the Error message [1]: https://i.stack.imgur.com/lJCyQ.jpg
It looks like your projectId is incomplete (it should be eight characters but there are only seven) in your client configuration. You're getting a CORS error because you're trying to get data from a project that doesn't have CORS origins set (since it doesn't exist).
I had a CORS problem too - I had added https://localhost:3000/ to CORS origins in Sanity.io with Credentials set to allowed but still got the error. My mistake was having the wrong Project ID.
(**Note I'm using ViteJS instead of NPM)
Click on the copy beside the Project ID ->
Then paste it in your .env file, right beside REACT_APP_SANITY_PROJECT_ID
Finally, in your Sanity client.js file make sure you are pointing to the correct environment variable.

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

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

still having cors issue after adding Access-Control-Allow-Origin header in apache2

I added following lines to my apache2.conf file for solving the cors issue.
<Directory /var/www/html/rcycLatest2/RCYC/presentation/angular/rcyc>
Header set Access-Control-Allow-Origin "http://localhost:4200"
</Directory>
but it still showing following error
Failed to load http://localhost/angular5/lesson2.pdf: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
I also tried with '*' in place of Access-Control-Allow-Origin url,but it still showing same error.I already spend one day in this issue,can someone please help me to solve this issue.
I can suggest 2 options:
option 1:
If your backend server is node (or if you just started a project and don't mind to a rapid install of node):
I would recommend you use Express.js, this would be the quickest setup for a REST API on your local and you will see how easily I set cors right:
let express = require('express');
let cors = require('cors');//<= CORS package install this with "npm i cors" in your console
let app = express();
app.use(cors()); //<== this solves your cors issue
app.get('/', (req,res) => {
console.log('ready and listening on port 3000');
res.send('hello there, cors issue solved!);
});
app.listen(3000);
once you run this index.js, your Node server would be located at http://localhost:3000
options 2:
Another route to take, and TBH a much faster one, would be to use the Moesif Origin Extension, suffice to say that you would need chrome for this.
Godspeed.

Resources