mardi 5 janvier 2021

How to turn off cors in pure nodejs server

I have created a server without express , with pure node.js like this

const server = http.createServer(async (req, res) => { ...

Now if i try to access one of my route over chrome i get cors error saying

Access to fetch at 'https://ift.tt/38i0V9e' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I am trying to turn it off by sending this headers but its not working

res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST");

I get the same error and i am not sure why

Inside my server i am first checking method and url like this

const { method, url } = req;
if (method == "GET" && url === "/myroute") { ...
...
res.end(data) 

And on my frontend i am accessing it using fetch API like this:

 const results = await fetch(`http://example.com/myroute`,{headers:{'auth':'someauthtoken'}})
  .then((res) => {
    return res.json();
  })

Also if i test it with postman its working and i can see this headers sent in response

Aucun commentaire:

Enregistrer un commentaire