抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

使用 koa-cors

  • Server.js 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    const Koa = require('koa');
    const bodyParser = require('koa-bodyparser'); //post数据处理
    const router = require('koa-router')(); //路由模块
    const cors = require('./libs/koa-cors'); //跨域处理文件koa-cors.js
    const app = new Koa();

    app.use(cors);

    router.post('/', async function (ctx) {
    ctx.body = '请求成功了'
    });

    app.listen(3000);
  • Koa-cors.js 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    /**
    * 关键点:
    * 1、如果需要支持 cookies,
    * Access-Control-Allow-Origin 不能设置为 *,
    * 并且 Access-Control-Allow-Credentials 需要设置为 true
    * (注意前端请求需要设置 withCredentials = true)
    * 2、当 method = OPTIONS 时, 属于预检(复杂请求), 当为预检时, 可以直接返回空响应体, 对应的 http 状态码为 204
    * 3、通过 Access-Control-Max-Age 可以设置预检结果的缓存, 单位(秒)
    * 4、通过 Access-Control-Allow-Headers 设置需要支持的跨域请求头
    * 5、通过 Access-Control-Allow-Methods 设置需要支持的跨域请求方法
    */

    module.exports = async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', '*'); //允许来自所有域名请求(不携带cookie请求可以用*,如果有携带cookie请求必须指定域名)
    // ctx.set("Access-Control-Allow-Origin", "http://localhost:8080"); // 只允许指定域名http://localhost:8080的请求

    ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE'); // 设置所允许的HTTP请求方法

    ctx.set('Access-Control-Allow-Headers', 'x-requested-with, accept, origin, content-type'); // 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段.
    // 服务器收到请求以后,检查了Origin、Access-Control-Request-Method和Access-Control-Request-Headers字段以后,确认允许跨源请求,就可以做出回应。

    ctx.set('Content-Type', 'application/json;charset=utf-8'); // Content-Type表示具体请求中的媒体类型信息

    ctx.set('Access-Control-Allow-Credentials', true); // 该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。
    // 当设置成允许请求携带cookie时,需要保证"Access-Control-Allow-Origin"是服务器有的域名,而不能是"*";

    ctx.set('Access-Control-Max-Age', 300); // 该字段可选,用来指定本次预检请求的有效期,单位为秒。
    // 当请求方法是PUT或DELETE等特殊方法或者Content-Type字段的类型是application/json时,服务器会提前发送一次请求进行验证
    // 下面的的设置只本次验证的有效时间,即在该时间段内服务端可以不用进行验证

    ctx.set('Access-Control-Expose-Headers', 'myData'); // 需要获取其他字段时,使用Access-Control-Expose-Headers,
    // getResponseHeader('myData')可以返回我们所需的值
    /*
    CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:
    Cache-Control、
    Content-Language、
    Content-Type、
    Expires、
    Last-Modified、
    Pragma。
    */

    /* 解决OPTIONS请求 */
    if (ctx.method == 'OPTIONS') {
    ctx.body = '';
    ctx.status = 204;
    } else {
    await next();
    }
    };

使用 koa2-cors

  1. 安装插件

    $ npm install koa2-cors

    或者

    $ yarn add koa2-cors

  2. Server.js 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    const Koa = require('koa');
    const bodyParser = require('koa-bodyparser'); //post数据处理
    const router = require('koa-router')(); //路由模块

    const cors = require('koa2-cors'); //跨域处理
    const app = new Koa();
    app.use(
    cors({
    origin: function(ctx) { //设置允许来自指定域名请求
    if (ctx.url === '/test') {
    return '*'; // 允许来自所有域名请求
    }

    //设置多域名
    const whiteList = ['http://zerow.cn','http://localhost:8081']; //可跨域白名单
    let url = ctx.header.referer.substr(0,ctx.header.referer.length - 1);
    if(whiteList.includes(url)){
    return url //注意,这里域名末尾不能带/,否则不成功,所以在之前我把/通过substr干掉了
    }

    return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
    },
    maxAge: 5, //指定本次预检请求的有效期,单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
    })
    );
    router.post('/', async function (ctx) {
    ctx.body = '请求成功了'
    });

    app.listen(3000);

评论