0

I'm currently developing a server using express with NodeJS, and I've ran into an issue with the CORS policy. In my servers code, I have

app.get(`/important`, function(req,res){
    fs.readFile('./json/important.json', `utf8`, function(err, data){
        console.log(data)
        res.set('Content-Type', 'application/json')
        res.status(200)
        res.end(data)
    })
})

And on my client running Vanilla Javascript I have

    fetch("http://127.0.0.1:3031/morbius")
        .then(result=>{
            console.log(result.json())
        })

Executing the fetch returns an error saying how the request has been blocked by the CORS policy, but if I understand what I'm doing, setting a header should prevent that from being an issue. Not sure what I'm doing wrong here.

gjoe
  • 99
  • 1
  • 1
  • 7
  • What CORS headers are you setting? What's the full error? – Evert Jul 29 '22 at 00:51
  • Have you configured the [cors middleware](https://expressjs.com/en/resources/middleware/cors.html)? FYI you can simplify your response with just `res.json(data)`. – Phil Jul 29 '22 at 01:06

1 Answers1

0

Comment from https://stackoverflow.com/users/283366/phil helped me solve the issue. Installing cors and running

app.use(cors())

Fixes the issue

gjoe
  • 99
  • 1
  • 1
  • 7