springMVC跨域问题


1、跨域问题:

按照网上所有的方法试了一遍,都没跨过去,正在无助之际,使用filter按照下面的方法解决的时候出现了转机:

添加filter:

package com.thc.bpm.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

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;
        HttpServletRequest request = (HttpServletRequest)servletRequest;
 
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Authentication");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){
            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
 
    @Override
    public void destroy() {
 
    }
}

在web.xml配置田间上面的过滤器:

    
        corsFilter
        com.thc.bpm.filter.CorsFilter
    
    
        corsFilter
        /*
    

springMVC跨域问题_第1张图片

测试的时候发现报错不一样了:
image
主要是这句话:Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response
大致翻译下意思是:请求头中有个字段“x-access-token”,这个字段不被预运行响应中的Access-Control-Allow-Headers所允许。
我忽然想到我们的token就是放在x-access-token这个字段中,而过滤器中相关设置为:

response.setHeader("Access-Control-Allow-Headers", "Authentication");

那就把Authentication换成x-access-token试试:

response.setHeader("Access-Control-Allow-Headers", "x-access-token");

springMVC跨域问题_第2张图片
再测试一次:

springMVC跨域问题_第3张图片

2、总结cors常见的header:

Access-Control-Allow-Origin: http://foo.org
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: GET,PUT, DELETE
Access-Control-Allow-Headers: content-type

"Access-Control-Allow-Origin"表明它允许"http://foo.org"发起跨域请求;
"Access-Control-Max-Age"表明在3628800秒内,不需要再发送预检验请求,可以缓存该结果;
"Access-Control-Allow-Methods"表明它允许GET、PUT、DELETE的外域请求;
"Access-Control-Allow-Headers"表明它允许跨域请求包含content-type头;

预检请求用的方法是OPTIONS,表示这个请求是用来询问的。关键字段是Origin,表示请求来自哪个源。
除了Origin之外,还有两个特殊字段:
Access-Control-Request-Method:该字段是必须的,用来列出CORS请求会用到那些方法。
Access-Control-Request-Headers:该字段是一个逗号分隔的字符串,指定浏览器CORS请求会额外发送的头信息字段。

你可能感兴趣的:(springMVC跨域问题)