honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
20.11k stars 574 forks source link

CORS no working #3453

Open LRboyz opened 1 month ago

LRboyz commented 1 month ago

What version of Hono are you using?

4.6.2

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

I have two projects running locally Front end: http://localhost:6035 Backend: http://localhost:3000 I configured cors on the backend, the following is my configuration: backend

import { cors } from "hono/cors";

const app = new Hono().basePath("/api");

// 添加 CORS 中間件
app.use(
  "/api/*",
  cors({
    origin: ["http://localhost:6035", "http://localhost"],
    allowHeaders: ["Origin", "Content-Type", "Authorization", "X-Custom-Header", "Upgrade-Insecure-Requests"], // 允許的 headers
    allowMethods: ["OPTIONS", "GET", "POST", "PATCH", "PUT", "DELETE"], // 允許的 HTTP 方法
    exposeHeaders: ["Content-Length"], // 暴露的 headers
    maxAge: 600, // 預檢請求的結果可以被快取多久(秒)
    credentials: true // 是否允許發送 cookies
  })
);

client:

  const sendHeartbeat = useCallback(async () => {
    try {
      await ofetch(`${BASE_URL}/api/v1/heart/${userId}`, {
        method: "POST",
        headers: {
            Authorization: `Bearer ${authToken}`, // 添加授权头
        },
        body: { message: "ping" },
      });
    } catch (error) {
      console.error("Failed to send heartbeat:", error);
    }
  }, [userId]);

  useEffect(() => {
    sendHeartbeat(); // Send initial heartbeat

    const intervalId = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);

    return () => clearInterval(intervalId); // Cleanup on component unmount
  }, [sendHeartbeat]);

And the backend received the options request from the frontend, but the status code was 204?: image And the front end still reports an error Cors: image image Did I do that step wrong? I tried all the methods mentioned in the issue but failed to solve the problem. I also tried deploying to vercel and the same thing happened. 🙏

What is the expected behavior?

httpCode: 200

What do you see instead?

httpCode: 204

Additional information

No response

yusukebe commented 1 month ago

Hi @LRboyz

Maybe this is not a bug. Please provide a minimal project to reproduce it. If not, we'll close this.