Configure the settings for CORS but CORS error is happened on Chrome. #3488
-
I use Hono for Web backend app. And I accessed backend app via frontend app, then CORS error occurred as the following screenshot. HTTP response status is 204 for the first preflight request, but CORS error occurred for the second actual request. According to the error message, it seems to be caused by It seems CORS headers is required in the response for the actual request. I solved this error by explicitly writing code to return CORS headers. Sample code is here. But I am wondering why I have to explicitly write code that returns CORS headers. Can I configure CORS setting without code that returns CORS headers ? import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { cors } from "hono/cors";
app.post("/signin", (c) => {
c.header("Access-Control-Allow-Origin", "http://localhost:4173");
c.header("Access-Control-Allow-Credentials", "true");
setCookie(c, "session_token", SessionToken);
c.status(201);
return c.body("this is body");
});
app.use(
cors({
origin: ["http://localhost:4173"],
credentials: true,
})
);
const port = 3000;
console.log(`Server is running on port ${port}`);
serve({
fetch: app.fetch,
port,
}); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This seems like a simple issue of ordering. In the code you provided, you are "using" the CORS middleware after the route. If you switch these around, you do not need to set the headers explicitly like so: app.use(
cors({
origin: ["http://localhost:4173"],
credentials: true,
}),
);
app.post("/signin", c => {
c.status(201);
return c.body("this is body");
});
const port = 3000;
console.log(`Server is running on port ${port}`);
serve({
fetch: app.fetch,
port,
}); |
Beta Was this translation helpful? Give feedback.
-
Appreciate your response. |
Beta Was this translation helpful? Give feedback.
This seems like a simple issue of ordering. In the code you provided, you are "using" the CORS middleware after the route. If you switch these around, you do not need to set the headers explicitly like so: