分别在SpringBoot和Vue中解决跨域问题

一、为什么会出现跨域问题

出于浏览器的同源策略。

同源策略是一种约定,它是浏览器最核心也是最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的JavaScript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域),就是两个页面具有相同的协议protocol、主机host和端口号port。

二、当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域

当前页面url 被请求页面url 是否跨域 原因
http://www.test.com/ http://www.test.com/index.html 同源(协议、域名、端口号相同)
http://www.test.com/ https://www.test.com/index.html 跨域 协议不同(http/https)
http://www.test.com/ http://www.baidu.com/ 跨域 主域名不同(test/baidu)
http://www.test.com/ http://blog.test.com/ 跨域 子域名不同(www/blog)
http://www.test.com:8080/ http://www.test.com:7001/ 跨域 端口号不同(8080/7001)

三、非同源限制

  1. 无法读取非同源网页的cookie、localstorage和indexedDB
  2. 无法接触非同源网页的DOM
  3. 无法向非同源地址发送AJAX请求
  4. 无法进行controller接口调用

四、解决跨域问题的五种方式

1、SpringBoot中@Configuration解决跨域(推荐)

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.cors.CorsConfiguration;  
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;  
import org.springframework.web.filter.CorsFilter;  
  
@Configuration  
public class CorsConfig {
    @Bean  
    public CorsFilter corsFilter() {  
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
        source.registerCorsConfiguration("/**", buildConfig()); 
        return new CorsFilter(source);  
    }  
    
   private CorsConfiguration buildConfig() {  
        CorsConfiguration corsConfiguration = new CorsConfiguration();  
        // 1允许任何域名使用
        corsConfiguration.addAllowedOrigin("*"); 
        // 2允许任何头
        corsConfiguration.addAllowedHeader("*"); 
         // 3允许任何方法(post、get等) 
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;  
    }  
}

2、手写过滤器

package com.ninesword.utils;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CrossFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(CrossFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        logger.debug("跨域请求进来了。。。");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        httpServletRequest.getSession();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Content-type", "application/json");
        httpResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
        chain.doFilter(request, httpResponse);
    }
}

在web.xml中配置过滤器和需要过滤的接口

<!-- 添加过滤器过滤跨域请求 -->
 <filter>
   <filter-name>cors</filter-name>
   <!-- 这里配置上面刚刚设置的java过滤器文件 -->
   <filter-class>com.ninesword.utils.CrossFilter</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>cors</filter-name>
   <!-- 这里配置你需要进行跨域的接口,*代表jsForSdp当前路径下所子有路径 -->
   <url-pattern>/jsForSdp/*</url-pattern>
 </filter-mapping>

经过以上配置,已经可以成功跨域了。

3、使用Spring拦截器解决跨域问题

package com.test.test.conf;

import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;

//拦截器添加跨域支持(如果是web.xml配置拦截器,请将@component删除)
@Component
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

web.xml中

<!--解决跨域访问-->
<filter>
    <filter-name>crossorigin</filter-name>
    <filter-class>com.test.test.crossorigin</filter-class>
</filter>
<filter-mapping>
    <filter-name>crossorigin</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4、JSONP实现(仅适用于GET请求,不推荐使用,详细请见六前端中跨域的解决方法)

5、注解实现

(1)从Spring MVC 4.2 开始增加支持跨域访问。

在方法或类上增加@CrossOrigin注解。

其中@CrossOrigin中的2个参数:

  1. origins  : 允许可访问的域列表
  2.  maxAge:飞行前响应的缓存持续时间的最大年龄(以秒为单位)。

(2)自定义规则支持全局跨域访问

在spring-mvc.xml文件中配置映射路径,如下:

<mvc:cors>  
    <mvc:mapping path="/cross/*"/>  
</mvc:cors> 

如果整个项目所有方法都可以访问,则可以这样配置

<mvc:cors>    
    <mvc:mapping path="/**"/>    
</mvc:cors> 

其中* 表示匹配到下一层

** 表示后面不管有多少层,都能匹配。

6、nginx实现

五、前端中跨域的解决方法

1、设置document.domain解决无法读取非同源网页的cookie问题

 因为浏览器是通过document.domain属性来检查两个网页是否同源,因此只要通过设置相同的document.domain,两个网页就可以共享cookie(此方案仅限主域相同,子域不同的跨域应用场景。)


// 两个页面都设置
document.domain = 'test.com';

2、跨文档通信API:window.postMessage()

调用postMessage方法实现父窗口http://test1.com向子窗口http://test2.com发消息(子窗口同样可以通过该方法发送消息给父窗口)

它可以用于解决以下方面的问题:

  1. 页面和其打开的新窗口的数据传递
  2. 多窗口之间消息传递
  3. 页面与嵌套的iframe消息传递
  4. 上面三个场景的跨域数据传递
// 父窗口打开一个子窗口
var openWindow = window.open('http://test2.com', 'title');
 
// 父窗口向子窗口发消息(第一个参数代表发送的内容,第二个参数代表接收消息窗口的url)
openWindow.postMessage('Nice to meet you!', 'http://test2.com');

调用message事件,监听对方发送的消息

// 监听 message 消息
window.addEventListener('message', function (e) {
  console.log(e.source); // e.source 发送消息的窗口
  console.log(e.origin); // e.origin 消息发向的网址
  console.log(e.data);   // e.data   发送的消息
},false);

3、JSONP

JSONP是服务器与客户端跨源通信的常用方法。

最大特点就是简单,兼容性好,缺点是只支持get请求,不支持post请求。

核心思想:网页通过添加一个<script>元素,向服务器请求JSON数据,服务器收到请求后,将数据放在一个指定名称的回调函数的参数位置传回来。

①原生实现

<script src="http://test.com/data.php?callback=dosomething"></script>
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
 
// 处理服务器返回回调函数的数据
<script type="text/javascript">
    function dosomething(res){
        // 处理获得的数据
        console.log(res.data)
    }
</script>

②jQuery ajax

$.ajax({
    url: 'http://www.test.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 请求方式为jsonp
    jsonpCallback: "handleCallback",    // 自定义回调函数名
    data: {}
});

③Vue.js

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) => {
    console.log(res); 
})

4、CORS

CORS是跨域资源分享的缩写。它是W3C标准,属于跨源AJAX请求的根本解决方法。

  1. 普通跨域请求:只需服务器端设置Access-Control-Allow-Origin
  2. 带cookie跨域请求:前后端都需要进行设置

【前端设置】根据xhr.withCredentials字段判断是否带有cookie

(1)原生AJAX

var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
 
// 前端设置是否带cookie
xhr.withCredentials = true;
 
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
 
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};

②jQuery ajax 

$.ajax({
   url: 'http://www.test.com:8080/login',
   type: 'get',
   data: {},
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,   // 会让请求头中包含跨域的额外信息,但不会含cookie
});

③vue-resource

Vue.http.options.credentials = true

④ axios 

axios.defaults.withCredentials = true

【服务端设置】

服务端对于CORS的支持,主要是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许ajax进行跨域访问。

① Java后台

/*
 * 导入包:import javax.servlet.http.HttpServletResponse;
 * 接口参数中定义:HttpServletResponse response
 */
 
// 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加'/'
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); 
 
// 允许前端带认证cookie:启用此项后,上面的域名不能为'*',必须指定具体的域名,否则浏览器会提示
response.setHeader("Access-Control-Allow-Credentials", "true"); 
 
// 提示OPTIONS预检时,后端需要设置的两个常用自定义头
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");

② Nodejs后台

var http = require('http');
var server = http.createServer();
var qs = require('querystring');
 
server.on('request', function(req, res) {
    var postData = '';
 
    // 数据块接收中
    req.addListener('data', function(chunk) {
        postData += chunk;
    });
 
    // 数据接收完毕
    req.addListener('end', function() {
        postData = qs.parse(postData);
 
        // 跨域后台设置
        res.writeHead(200, {
            'Access-Control-Allow-Credentials': 'true',     // 后端允许发送Cookie
            'Access-Control-Allow-Origin': 'http://www.domain1.com',    // 允许访问的域(协议+域名+端口)
            /* 
             * 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
             * 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
             */
            'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly'  // HttpOnly的作用是让js无法读取cookie
        });
 
        res.write(JSON.stringify(postData));
        res.end();
    });
});
 
server.listen('8080');
console.log('Server is running at port 8080...');

③ Apache需要使用mod_headers模块来激活HTTP头的设置,它默认是激活的。你只需要在Apache配置文件的<Directory>, <Location>, <Files>或<VirtualHost>的配置里加入以下内容即可

Header set Access-Control-Allow-Origin *

上一篇:Java基础知识总结(绝对经典)

下一篇:【全栈最全Java框架总结】SSH、SSM、Springboot

猜你喜欢

转载自blog.csdn.net/guorui_java/article/details/109874891