I\'m not able to correctly handle CORS issues when doing either PATCH
/POST
/PUT
requests from the browser sending an Authorization
The accepted answer did not work for me. However vercel now appear to have updated their advice, with their example code being:
const allowCors = fn => async (req, res) => {
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Allow-Origin', '*')
// another option
// res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS')
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)
if (req.method === 'OPTIONS') {
res.status(200).end()
return
}
return await fn(req, res)
}
const handler = (req, res) => {
const d = new Date()
res.end(d.toString())
}
module.exports = allowCors(handler)
It's worth saying I'm not entirely sure of the difference between res.end
and res.send
but to actually ingest the response into my front end (React) I changed the handler
function to:
const handler = (req, res) => {
const d = {data: "Hello World"};
res.send(d)
}
which allowed me to ingest in React as:
function getAPIHelloWorld () {
let connectStr = "/api"
fetch(connectStr)
.then(response => response.json())
.then(response => {console.log(response.data)})
.catch(err => console.error(err))
}