You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@fastify/cors时预检请求返回404,跨域访问受阻求助

Fastify 搭配 @fastify/cors 出现前端跨域错误,Postman/Insomnia 请求正常

我用 Fastify 搭建了简易后端,代码如下:

export class HttpServer {
    async start() {
        try {
            const fastify = Fastify();
            await fastify.register(cors);
            fastify.post('/auth/login', loginRoute);
            fastify.post('/auth/refresh', refreshRoute);
            fastify.get('/user/current', { preHandler: authMiddleware }, getCurrentUser);
            await fastify.listen({ port: 4001, host: "0.0.0.0" });
            console.log(`🔥 [HttpServer]: Successfully started!`);
        } catch (err) {
            console.log(`😔 [HttpServer]: Not possible to start!`);
            process.exit(1);
        }
    }
}

入口文件仅执行:

await httpServer.start();

通过 Insomnia 等工具请求正常,但前端发起请求时触发 CORS 错误:

从源地址'http://localhost:3000'访问'http://localhost:4001/auth/login'的XMLHttpRequest被CORS策略阻止:预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'头。

前端使用 Axios 请求,代码如下:

import axios from "axios";

export function getAPI() {
    const api = axios.create({
        baseURL: 'http://localhost:4001'
    })
    return api;
}

调用方式:

const api = getAPI()
await api.post('/auth/login', {
  token
})
...

我尝试过多种 @fastify/cors 配置,甚至手动处理跨域逻辑都无效。用 Express 搭配 cors 包测试可正常工作,推测问题出在 Fastify 或 @fastify/cors。


解决方案

当时我是在 Bun 环境 中使用 Fastify,因无法正常解决跨域问题最终改用 Elysiajs,不确定当前 Fastify 是否已完全支持 Bun 环境。


内容的提问来源于stack exchange,提问作者jhnxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:40:15