解决项目中的跨域问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WKX18330698534/article/details/82811422

一、跨域是什么?

       解释跨域之前,先了解同源策略,简单描述是:域名,协议,端口相同。

      跨域的官方解释是:跨站http请求(Cross-site HTTP request),指发起请求的资源所在域不同于请求指向资源所在域的http请求,即不符合同源策略。

二、什么情况下需要跨域

从上面的表格中我们可以看出,协议、域名、端口三者之间任意一与当前页面地址不同都会引起跨域问题。

企业开发中出现跨域问题情况举例:

1、前后端分离的开发模式中,前后端联调,前端人员使用本地(http://localhost)调用后端准备的联调环境的服务(http:dmsdbj.com)。

2、当系统庞大,业务复杂时,很可能出现直接调用第三方的某些服务来完成业务功能。

三、解决方案

解决跨域有多种方法,在项目实战中使用过三种方式:Nginx,使用@CrossOrigin注解,过滤器

1、Nginx

使用Nginx做反向代理,www.baidu.com/index.html需要调用www.sina.com/server.php,可以写一个接口www.baidu.com/server.php;

站在巨人的肩膀上:https://www.cnblogs.com/bninp/p/5694277.html

2、@CrossOrigin注解

站在巨人肩膀上:https://www.cnblogs.com/mmzs/p/9167743.html

3、过滤器

使用CORS协议,在spring的web.xml中配置过滤器:

 <!--跨域过滤器 -->
    <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>Authorization,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>

推荐阅读:https://www.cnblogs.com/softidea/p/6108066.html 有源码分析

猜你喜欢

转载自blog.csdn.net/WKX18330698534/article/details/82811422