TypechoJoeTheme

IT技术分享

统计

对服务器端进行设置以接受跨域请求(TOMCAT,NGINX)

2016-03-27
/
0 评论
/
748 阅读
/
正在检测是否收录...
03/27

因为JavaScript同源策略的限制,a.com 域名下的js无法操作b.com下的对象。凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。目前有很多解决跨域问题的方法,其中最著名的是CROS,那么如何通过在服务器端进行简单的配置,从而实现跨域问题呢?
本站内与该类问题相关的文章:

1、接口编程——前后台数据传输跨域问题的解决方法

2、HTTP协议中GET,POST,PUT,DELETE,OPTIONS请求的详细流程

一、TOMCAT服务器

1、创建文件

在tomcat服务器下webapps/ROOT目录下创建如下两个xml文件。

  • clientaccesspolicy.xml
<?xml version="1.0" encoding="utf-8" ?>
    <access-policy>
        <cross-domain-access>
            <policy>
                <allow-from http-request-headers="*">
                    <domain uri="*"/>
                </allow-from>
                <grant-to>
                    <resource path="/" include-subpaths="true"/>
                </grant-to>
            </policy>
        </cross-domain-access>
    </access-policy>
  • crossdomain.xml
<?xml version="1.0"?>

<cross-domain-policy>

    <allow-access-from domain="*" />

</cross-domain-policy>

2、在web.xml中配置过滤器

可以选择在Tomcat服务器下conf/web.xml,也可以是项目中的WEB-INF/web.xml。有两种方式支持过滤器,一种是使用tomcat自带的过滤器,另一种是使用cors-filter-1.7.jar,两者选其一即可。

  • 使用tomcat下自带的cors过滤器
<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.preflight.maxage</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  • 使用cors-filter-1.7.jar,还需要java-property-utils-1.9.jar
<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
         <param-name>cors.allowOrigin</param-name>
         <param-value>*</param-value>
    </init-param>
    <init-param>
         <param-name>cors.supportedMethods</param-name>
         <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
         <param-name>cors.supportedHeaders</param-name>
         <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
         <param-name>cors.exposedHeaders</param-name>
         <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
         <param-name>cors.supportsCredentials</param-name>
         <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

二、NGINX服务器

在/etc/nginx/sites-enabled下的相应文件中配置如下代码

#
# Wide-open CORS config for nginx
#
location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-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-CustomHeader,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' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-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-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }
}

三、PHP代码示例

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');

    }

}

四、JAVA代码示例

// java端支持跨域请求
public String execute(){
    //允许哪些url可以跨域请求到本域
    response.setHeader("Access-Control-Allow-Origin", "*");
    //允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONS
    response.setHeader("Access-Control-Allow-Methods","POST");
    //允许哪些请求头可以跨域
    response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");

    SiteHandlerAction SiteHandler = (SiteHandlerAction) BeansFactory.getBean(SiteHandlerAction.class);
    //所有的分类集合
    List list = SiteHandler.getAllIndustryCategory();
    //将list转为json
    JSONArray jsonArray = JSONArray.fromObject(list);
    //转为json字符串
    String json = jsonArray.toString();
    try {
        PrintWriter write = response.getWriter();
        write.print(json);
        write.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return NONE;
}

五、参考文献

相关链接

1、Apache Tomcat 9 Configuration Reference · Container Provided Filters

2、Enable-CORS · CORS on Nginx

朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1763/(转载时请注明本文出处及文章链接)