In my React app I am making a simple fetch request:
useEffect(() => {
fetch('http://localhost:3000/').then((response) => console.log('foobar', response));
}, []);
This works fine. But when I try this with my real url like https://my-site.com/abc/token it doesn't work? When I try to fetch a different domain it doesn't work?
What could be the issue and how do I solve this?
Not many details in the post but I'll give it a go.
If you are receiving an error whilst in development similar to the one pictured below, then it means the server you are trying to contact does not allow the host you are developing on. This can be fixed either by either changing the security settings of your browser or installing a plugin that disables CORS.
However, if you are receiving this error in a non-local environment, then it means you should add the hostname of your frontend into the Access-Control-Allow-Origin on the serverside (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).
Links for more details
Disable CORS in Chrome + Safari and the plugin for Firefox - https://medium.com/swlh/avoiding-cors-errors-on-localhost-in-2020-5a656ed8cefa
Plugin for Chrome - Why does my http://localhost CORS origin not work?
Related
TLDR: React app interfaces properly with Flask API on PythonAnywhere when hosted locally but not when a static build is hosted on Netlify. Perhaps the proxy information is missing from the build?
EDIT 1:
Here are the errors in the browser console:
I've created a Flask API that pulls machine learning models from Amazon S3 and returns predictions on data input from POST requests. I've put this API on PythonAnywhere.
I've also created a React frontend which allows me to input data, submit it, and then receive the prediction. When I host this app locally, it behaves appropriately (i.e. connecting to the Flask app on PythonAnywhere, loading the models properly, and returning the predictions).
I've tried deploying a static build of the React app on Netlify. It behaves as expected, except for anything that requires interacting with the Flask App. I have a button for testing that simply calls the Flask app in a GET request, and even this is throwing a 404 error.
I checked the error and server logs on PythonAnywhere and see nothing. The only thing I can thik of is that my proxy which lists the domain of the PythonAnywhere app in my package.json file is for some reason unincluded in the build, but I don't know why this would be the case.
Has anyone else run into a similar issue or know how I can check to see if the proxy information is included in the static build? Thanks in advance!
Thanks to #Glenn for the help.
Solution:
I realized (embarrassingly late) that the requests were not going to the right address, as can be seen in the browser console error above. I was using a proxy during development, so the netlify app was calling itself rather than the pythonanywhere API. I simply went into my react code and edited the paths to pythonanywhere. E.g.
onClick={ async () => {
const response = await fetch("/get", {...}}
became
onClick={ async () => {
const response = await fetch("https://username.pythonanywhere.com/get", {...}}
As #Glenn mentioned, there may have been a CORS issue as well, so in my flask application I utilized flask_cors. I can't say for sure that this was necessary given that I didn't test removing it after the fetch addresses had changed, but I suspect that it is necessary.
Hopefully this can help someone else
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
I have a React application (create-react-app) running on http://localhost:3000/ and I need to send a request to an API (Java with Spring Boot) that is available on "https://review-feature-...api/partner".
However, when I send the request, I get the following error on my Chrome console:
POST https://review-feature-...api/partner net::ERR_CERT_AUTHORITY_INVALID
I've tried to change my React application to run on https://localhost:3000, but it doesn't work because I have a Keycloak authorization server running behind my React app, so I have to find a way to send the request using http://localhost:3000/ anyway.
I've also tried to use the following environment variables (How can I provide a SSL certificate with create-react-app?) but it doens't work.
SSL_CRT_FILE=.cert/server.crt
SSL_KEY_FILE=.cert/server.key
Thanks in advance.
I am running into a CORS issue when trying to have my React app send post requests to an api endpoint while using localhost:3000.
How do I configure my app to use custom.domain.dev instead of localhost:3000?
I have /etc/hosts setup to to include 127.0.0.1 custom.domain.dev as well as my .env file to include HOST=custom.domain.dev.
As noted in this stackoverflow question,
Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).
I think there are two parts of the question -
Regarding the CORS flag on local host
CORS flag is raised by the Browser when there is a request from a domain/port to an entire new domain/port. If you are doing this for testing, you can disable this security flag in chrome by adding the --disable-web-security flag. Just create a shortcut of chrome to desktop > Right click > Properties >In shortcut tab - Target > Append --disable-web-security --user-data-dir="C:\tmpChromeSession" to target. This will disable the CORS check.
In real cases, if you have access/control on the api server, what you should be doing is to enable CORS on server by adding necessary response headers (Access-Control-Allow-Origin) to the response. If you do not have access, one option will be to route the request through a CORS proxy.
Change port
You can change the running port of the react app on the package.json See this Stack Overflow answer. If you run the app on your machine, you are stuck with localhost.
I've created an Ionic app which calls an API to post the user's current location.
The request works as follows:
POST: http://mywebsite.com/api/Patients/AddLocation/17
with body:
{
"Latitude": 51.3753786,
"Longitude": -0.0833691
}
However, the following code in my Ionic app does work:
$http.post('http://mywebsite.com/api/Patients/AddLocation/' + $scope.id, data)
.success(function () {
console.log('Updated location');
})
.error(function (error) {
console.log('Error updating location');
console.log("Error: " + error);
});
In which 'data' is the same as the body above.
Any ideas why this isn't working?
UPDATE:
Here's a couple of screenshots of the network request:
Network request available at imgur RWNDF.png
Postman request
It happens if you have not enabled cors in your server.
enable cors in you server.
even if you dont enable cors,
get method will work peerfectly if you have enabled cors using any extension in chrome.
It's because of CORS. Enable cros from the server end and the a header will be set in HTTP Access-Control-Allow-Origin: * .
If your server app is an expressjs app, use below code to enable CORS
var cors = require('cors');
.....
app.use(cors());
Else use chrome extension Allow Cross Origin Request
This should solve the problem
After comparing this to a sister app which uses the same API and works, the only difference I could see was that a few of the plugins were different.
To remedy this I deleted the plugins folder and the platforms folder, re-added android and just the plugins I need, it now works. I guess it's maybe some bug I created by using the wrong mixture of plugins.
A very unsatisfying answer, but all requests work now!