设置 CORS 实现跨域请求

一、使用php代码实现

#
# CORS config for php
# Code by rehiy[[email protected]]
#

function make_cors($origin = '*') {

    $request_method = $_SERVER['REQUEST_METHOD'];

    if ($request_method === 'OPTIONS') {

        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Methods:GET, POST, OPTIONS');

        header('Access-Control-Max-Age:1728000');
        header('Content-Type:text/plain charset=UTF-8');
        header('Content-Length: 0',true);

        header('status: 204');
        header('HTTP/1.0 204 No Content');

    }

    if ($request_method === 'POST') {

        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Methods:GET, POST, OPTIONS');

    }

    if ($request_method === 'GET') {

        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Methods:GET, POST, OPTIONS');

    }

}

二、使用nginx配置实现

#
# CORS config for nginx
# Code by rehiy[[email protected]]
#

location / {

    set $origin '*';

    if ($request_method = 'OPTIONS') {

        add_header 'Access-Control-Allow-Origin' $origin;

        #
        # Om nom nom cookies
        #
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;

        return 204;

    }

    if ($request_method = 'POST') {

        add_header 'Access-Control-Allow-Origin' $origin;
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

    }

    if ($request_method = 'GET') {

        add_header 'Access-Control-Allow-Origin' $origin;
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

    }

}
文章作者: 若海; 原文链接: https://www.rehiy.com/post/92/; 转载需声明来自技术写真 - 若海

添加新评论