-1

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:

  1. I contacted support. It is not an issue on their end since it looks like they support CORS. enter image description here

  2. 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.

Matthew Francis
  • 670
  • 3
  • 10
  • 26
  • Does this answer your question? [Zeit (Vercel) Now serverless authenticated requests failing because of CORS](https://stackoverflow.com/questions/61217119/zeit-vercel-now-serverless-authenticated-requests-failing-because-of-cors) – Concrete_Buddha Aug 16 '20 at 11:09
  • Yes! that's where I got my code and it helped me solved it:) @Concrete_Buddha – Matthew Francis Aug 16 '20 at 17:48

1 Answers1

0

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.

Burger
  • 24
  • 1