i have a post request on my at http://localhost:3000 and request resources from http://localhost:5500 even after allowing all origins it gives error. I’m stuck on this for a few hours now please help.
i get this error
JavaScript
x
4
1
Access to fetch at 'http://localhost:3000/upload' from origin 'http://localhost:5500' has been blocked
2
by CORS policy:
3
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
4
this is where i’m setting my header
JavaScript
1
12
12
1
app.all("*", (req, res, next) => {
2
// CORS headers
3
res.header("Access-Control-Allow-Origin", "*");
4
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
5
res.header("Access-Control-Allow-Credentials", "true");
6
res.header(
7
"Access-Control-Allow-Headers",
8
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization , client-security-token"
9
);
10
next();
11
});
12
this is my fetch request
JavaScript
1
11
11
1
const resp = await fetch("http://localhost:3000/upload", {
2
method: "POST",
3
headers: {
4
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
5
accept: "application/json",
6
},
7
body: formData,
8
});
9
const data = await resp.json();
10
console.log(data);
11
Advertisement
Answer
Try below.
Added a condition to check if the request type is OPTIONS
and then return response with status 200
.
JavaScript
1
17
17
1
app.all("*", (req, res, next) => {
2
// CORS headers
3
res.header("Access-Control-Allow-Origin", "*");
4
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
5
res.header("Access-Control-Allow-Credentials", "true");
6
res.header(
7
"Access-Control-Allow-Headers",
8
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization , client-security-token"
9
);
10
if (req.method === "OPTIONS") {
11
return res.status(200).end();
12
}
13
14
next();
15
});
16
17