Situation
I hosted my JSON database with Vercel, The database is in db.json. I have a site where I want to create and delete objects in my database. I have configured Axios so that it can allow PUT, PATCH, DELETE requests.
const streams = axios.create({
// .. where we make our configurations
baseURL: "https://music-json-server.now.sh/db.json",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Request-Method": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Content-Type": "application/json",
},
});
Problem I am met with errors related to CORS/axios config when starting the app.
xhr.js:126 Refused to set unsafe header "Access-Control-Request-Method"
Access to XMLHttpRequest at 'https://music-json-server.now.sh/db.json/' from origin 'http://localhost:3001' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
CORS is blocking the app from starting up.
What I have tried to fix this:
I contacted support. It is not an issue on their end since it looks like they support CORS.
Reading a related post, Zeit (Vercel) Now serverless authenticated requests failing because of CORS . Suggesting to add now.json. I don't think it applies to my situation since it uses serverless functions from Vercel.
Oh there is a package that you have to install and use: https://expressjs.com/en/resources/middleware/cors.html Follow this guide and you will be good to go.