ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

cloudflare使用express实现api防止跨域cors

2026/8/11 13:32:31 拓冰建站 浏览量
cloudflare使用express实现api防止跨域cors

在 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(); }

然后配置中间件在所有的路由前面:

然后重启项目,再次发送请求就没事了: