koa2-cors

源代码

// Type definitions for koa2-cors 2.0
// Project: https://github.com/zadzbw/koa2-cors#readme
// Definitions by: xialeistudio <https://github.com/xialeistudio>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

import * as Koa from 'koa';
declare namespace cors {
    interface Options {
        origin?: string | ((ctx: Koa.Context) => boolean | string);
        exposeHeaders?: string[];
        maxAge?: number;
        credentials?: boolean;
        allowMethods?: string[];
        allowHeaders?: string[];
    }
}

declare function cors(options?: cors.Options): Koa.Middleware;

export = cors;

判断是否允许跨域等问题

app.use(
    cors({
        origin: function(ctx) { //设置允许来自指定域名请求
            if (ctx.url === '/test') {
                return '*'; // 允许来自所有域名请求
            }
            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'] //设置获取其他自定义字段
    })
);
发布了71 篇原创文章 · 获赞 21 · 访问量 3657

猜你喜欢

转载自blog.csdn.net/qq_26386437/article/details/104434054