cloudflare使用express实现api防止跨域cors
大家好,我是1024小神,想进 技术群 / 私活群 / 股票群 或 交朋友都可以私信我,如果你觉得本文有用,一键三连 (点赞、评论、关注),就是对我最大的支持~
![]()
在 Cloudflare Workers 上,必须自己处理 CORS,Express 默认的 cors 中间件 并不会自动生效。
在中间件中写一个cors.ts文件,里面的代码如下:
import { Request, Response, NextFunction } from 'express';
export function corsMiddleware(req: Request, res: Response, next: NextFunction) {
// ⚠️ in production, write the specific domain
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
// handle preflight request
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
// next middleware
next();
}
然后配置中间件在所有的路由前面:
![]()
然后重启项目,再次发送请求就没事了:
![]()