本节内容已在网络篇详解跨域之CORS
设置跨域的中间件
const allowOrigins = ['http://localhost:3333', null]module.exports = function (req, res, next) {// 处理预检请求if (req.method === 'OPTIONS') {res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);res.header("Access-Control-Allow-Headers", req.headers['access-control-request-headers']);//允许的header类型}// 处理附带身份凭证的请求(cookie)res.header("Access-Control-Allow-Credentials", true)// 处理简单请求if ('origin' in req.headers && allowOrigins.includes(req.headers.origin)) {res.header("Access-Control-Allow-Origin", req.headers.origin);}next();}
