I’ve been stuck on this for past 2 days. I found numerous questions and articles surrounding this. I tried every possible solution out there. But can’t seem to understand what or why I keep getting CORS error even tho I’ve the origin setup on my backend and it WORKS for all the other requests except this one POST request.
has been blocked by CORS policy: 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.
My preflight request comes back with a 200 Ok but then the POST request fails with 500 code.
- Preflight request
- POST request
These are the solutions I tried and failed:
- Removed the header from the client request to avoid pre-flight request.
- Cors enabled on the backend with headers.
- Tried giving
apps.options('/api/execute', cors(corsOptions))
specific to that route. - Added proxy to vite.config AND package.json separately.
This is my POST request from frontend React:
async function executeCodeRequest() {
try {
let body = { problemId, code };
const response = await fetch(`${import.meta.env.VITE_BACKEND_DOMAIN}/api/execute`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(body)
});
return await response.json();
} catch (error) {
throw new Error(error);
}
}
CORS config on my express backend:
const corsOptions = {
origin: process.env.VERCEL_FRONTEND,
allowedHeaders: 'Content-Type',
methods: 'GET,OPTIONS,POST,DELETE',
preflightContinue: true,
credentials: true,
optionSuccessStatus:200,
}
app.use(cors(corsOptions));
both servers are hosted on Vercel (if that makes any difference). Any help would be appreciated. Been stuck on this longer than I’d want to. Really frustrating.
PS : this code works completely fine on my localhost:port servers. Only facing this in production.
1