Dealing with a POST request in my NextJS application has been challenging. This particular post request is originating from a different domain.
To address this issue, I included a receptor.ts
file in the /pages/api
directory:
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
console.log('POST')
const message = req.body.message;
console.log(`Message: ${message}`);
res.status(200).json({ message: "Ok" });
} else {
res.status(405).json({ error: "Not allowed" });
}
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
}
And here is how it's being utilized from the other app:
const url = `http://localhost:3000/api/receptor`;
const data = { message: "Hello" };
fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
The following error appears in the browser's console:
Access to fetch at 'http://localhost:3000/api/receptor' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Additionally, the IDE's console shows:
error - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I have tried adding mode: "no-cors"
to the request, but encountered the same errors. Any advice on resolving this situation?
SOLUTION
import { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
if (req.method === 'POST') {
console.log('POST')
const message = req.body.message;
console.log(`Message: ${message}`);
res.status(200).json({ message: "Ok" });
} else {
res.status(405).json({ error: "Not allowed" });
}
}
The underlying issue was not addressing the preflight request. The provided solution resolves this, and I will recommend closing the matter.