A better solution for this is to proxy the API Calls for your React App. Create React App provides you with a solution.
Before anything, I would like to tell that this method applies only for the applications that are created using Create React App and also this proxying works only on the development environment as a development feature and is not available for the production build. You just need to add a new key to the package.json
called proxy
and then restart the server.
"proxy": "http://localhost:8000/",
Now, your complete package.json
file looks something like this.
{
"name": "project-name",
"version": "1.0.0",
"private": true,
"proxy": "http://localhost:8000/",
"dependencies": {
"react": "^16.8.4",
"react-scripts": "2.1.8"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
}
And for the DELETE
requests, you can just call:
handleDelete = item => {
axios
.delete(`/api/todos/${item.id}`, item)
.then(res => this.refreshList());
};
The above code will have nothing related to CORS.
From the manual...
Keep in mind that proxy
only has effect in development (with npm start
), and it is up to you to ensure that URLs like /api/todos
point to the right thing in production. You don’t have to use the /api
prefix. Any unrecognized request without a text/html
accept header will be redirected to the specified proxy
.
So it is indeed specific for development purposes and not for a production level use. This helps in working with the future, where there's this similar setup and avoids all the crazy localhost hacky architecture for gearing with the environment.
I wrote a blogpost detailing how to set this thing up - Using React's Proxy to get ahead of CORS & use HTTPS for API calls. Hope this helps.