CORS Error: Access-Control-Allow-Methods in Preflight Response
If you’ve ever encountered this error, it can be a real headache to figure out how to fix it. And if you’re like me, you’re not too concerned about limiting access to your site.
“Access to fetch at ‘https://…’ from origin ‘https://user.github.io’ has been blocked by CORS policy: Method DELETE (PUT / POST) is not allowed by Access-Control-Allow-Methods in preflight response”, “Failed to load resource: net::ERR_FAILED”, “Uncaught (in promise) TypeError: Failed to fetch”
Even if don’t plan to restrict access to a URL with CORS, these steps will enable you to override any restrictions when trying to fetch from your backend API using a Create React App.
Backend
- Refactor your backend by first running…
npm i cors
2. Add cors to your Dependencies:
const cors = require('cors');
3. At the top of your Middleware, set app.options to *, which allows access from everywhere.
app.options('*', cors())
4. In app.use, set headers to Access-Control-Allow-Origin and Headers to allow access (Lines 49–53) before calling next().
res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
If your backend is hosted separately from the frontend, make sure to redeploy.
Frontend
5. After setting up the backend properly, set the headers in the async / await to the following for each other the methods you use (DELETE, POST, PUT):
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Z-Key',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, PUT, DELETE, OPTIONS'}
From there, run npm deploy if those scripts are already set up and push up to Github or wherever you’re uploading your code and see if it works!