Reputation: 1521
I was having trouble sending post requests with content-type application/json to my backend due to cors restrictions. I've started using 'cors' module and also enabled pre-flight requests for these routes.
My requests will now be answered and processed properly but I'll still get the following error on my console, which I'm not sure if it has side effects I'm not aware of.
Method OPTIONS is not allowed by Access-Control-Allow-Methods in preflight response.
OPTIONS https://example.com/api/postRequest net::ERR_FAILED
const cors = require('cors');
const corsOptions = {
origin: 'https://example.com',
optionsSuccessStatus: 200,
};
app.options('/api/postRequest', cors(corsOptions), function (req, res, next) {
res.header("Access-Control-Allow-Methods", "*");
res.setHeader('Content-Type', 'application/json');
next()
})
app.post('/api/postRequest', cors(corsOptions), async (req, res) => {
res.header("Access-Control-Allow-Methods", "*");
res.setHeader('Content-Type', 'application/json');
//do other stuff and send response
}
Upvotes: 0
Views: 849
Reputation: 1426
To enable all http methods, use:
const corsOptions = {
origin: 'https://example.com',
optionsSuccessStatus: 200,
methods: '*'
};
Upvotes: 1