使用@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
相关产品推荐
相关产品推荐

