express
express copied to clipboard
Can not set response headers when send a json body in a options request
By example:
router.options('/', (req, res, next) => {
res
.status(200)
.setHeader('Access-Control-Allow-Methods', allowFor('/')) // Without this line works fine.
.json({
schema: schemafor('/')
});
});
Says:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (node:_http_outgoing:652:11) at ServerResponse.header (/.../node_modules/express/lib/response.js:794:10) at sendOptionsResponse (/.../node_modules/express/lib/router/index.js:654:9) at Immediate. (/.../node_modules/express/lib/router/index.js:167:7) at Immediate.proxy (/.../node_modules/express/lib/router/index.js:671:8) at process.processImmediate (node:internal/timers:480:21)
The RFC allows the return of http content for options requests. I use it to return crud data schema settings for the frontend and allowed methods for show or hide pages in the dashboard.