Use a middleware...
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
But make sure you use it before your API method. Like this:
const app = express()
// middleware
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
// api
app.get('/user', (req, res, next) => {
service.doSomething
.then(data => res.send(data))
.catch(next)
})
app.use(handleError)
Took me a while to figure it out. I didn't see it mentioned anywhere so adding this to complement previous answers.