环企首页
cors
概述
cors 是 Express/Fastify 等 Node.js 框架处理跨域资源共享(CORS)的中间件。通过设置 HTTP 响应头,告诉浏览器允许哪些来源的页面访问当前 API。
为什么需要: 浏览器的同源策略(Same-Origin Policy)默认禁止网页从 A 域请求 B 域的 API,CORS 头让服务端声明允许哪些来源访问。
安装:
npm install cors
核心函数
cors(options) — 全局启用
const cors = require('cors')
app.use(cors()) // 允许所有来源(开发用)
常用选项
// 允许特定来源
app.use(cors({ origin: 'https://example.com' }))
// 允许多个来源
app.use(cors({
origin: ['https://example.com', 'https://app.example.com']
}))
// 函数动态判断(允许所有,带 credentials)
app.use(cors({
origin: (req, callback) => {
const allowed = ['https://a.com', 'https://b.com']
callback(null, allowed.includes(req.headers.origin))
},
credentials: true // 允许携带 Cookie
}))
// 正则匹配
app.use(cors({
origin: /example\.(com|org)$/ // 匹配 example.com / example.org
}))
// 仅允许特定方法
app.use(cors({
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['X-Total-Count'], // 允许前端访问的响应头
maxAge: 86400 // 预检请求(OPTIONS)缓存时间(秒)
}))
路由级配置
// 全部允许
app.get('/public', cors(), (req, res) => { res.json({}) })
// 仅允许特定来源
app.post('/admin', cors({ origin: 'https://admin.example.com' }), (req, res) => {
res.json({})
})
// 仅允许携带凭证
app.get('/profile', cors({ origin: true, credentials: true }), (req, res) => {
res.json({})
})
前端配合
// fetch 带凭证
fetch('https://api.example.com/data', {
credentials: 'include' // 携带 Cookie
})
// axios
axios.get('https://api.example.com/data', { withCredentials: true })
常见问题
| 问题 | 解决方案 |
|---|---|
| 预检请求(OPTIONS)返回 404 | 确保 OPTIONS 请求能被处理:app.options('*', cors()) |
携带 Cookie 但 origin: '*' 不生效 |
origin 不能是 *,需设为具体域名或 true |
| 跨域请求被拦截 | 确认服务端设置了正确的 Access-Control-Allow-Origin |
| 想禁止某个路由的 CORS | 路由中不挂载 cors() 或显式设置 origin: false |