本节内容已在网络篇详解跨域之CORS

    设置跨域的中间件

    1. const allowOrigins = ['http://localhost:3333', null]
    2. module.exports = function (req, res, next) {
    3. // 处理预检请求
    4. if (req.method === 'OPTIONS') {
    5. res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
    6. res.header("Access-Control-Allow-Headers", req.headers['access-control-request-headers']);//允许的header类型
    7. }
    8. // 处理附带身份凭证的请求(cookie)
    9. res.header("Access-Control-Allow-Credentials", true)
    10. // 处理简单请求
    11. if ('origin' in req.headers && allowOrigins.includes(req.headers.origin)) {
    12. res.header("Access-Control-Allow-Origin", req.headers.origin);
    13. }
    14. next();
    15. }