spring boot 设置允许跨域访问遇到的问题解决

        前后端分离的项目中会涉及到跨域访问的问题,我这里后端采用的是spring boot框架,可以在过滤器中添加允许跨域的设置

//设置允许跨域访问
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600"); 
response.setHeader("Access-Control-Allow-Headers", "*"); 

        但是,设置的response.setHeader("Access-Control-Allow-Headers", "*");并没有解决问题,浏览器还是会报跨域(CROS)的问题,经过反复调试,将常见的header值加到Access-Control-Allow-Headers中后进行测试,居然不报错了,我也不知道为什么*号不行,*号不应该就是代表全部吗? 知道问题的小哥哥小姐姐麻烦在评论区解释一下!

 response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization,"
            + " Content-Type, Accept, Connection, User-Agent, Cookie");

        有个需求是需要在header中加一个token参数,所以,还需要将token添加到Access-Control-Allow-Headers

 response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization,"
            + " Content-Type, Accept, Connection, User-Agent, Cookie, token");

        加了之后在请求具体的接口之前浏览器会执行一次OPTIONS请求来探测该请求是否被允许,在过滤器中判断如果当前请求方式是OPTIONS,直接放行即可!

//OPTIONS请求直接放行
if("OPTIONS".equals(request.getMethod())) {
    chain.doFilter(request, response);
    return;
}

        完整代码如下 :

package com.ldy.demo.common;

import java.io.IOException;
import java.io.PrintWriter;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;

import com.alibaba.fastjson.JSONObject;


@Order(1)
@WebFilter(filterName = "myWebFilter", urlPatterns = {"*"})
public class MyWebFilter implements Filter {
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	HttpServletResponse response = (HttpServletResponse) servletResponse;
		
	//设置允许跨域访问
	response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600"); 
        //response.setHeader("Access-Control-Allow-Headers", "*");  
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization,"
            + " Content-Type, Accept, Connection, User-Agent, Cookie,token");
        
        //OPTIONS请求直接放行
      	if("OPTIONS".equals(request.getMethod())) {
            chain.doFilter(request, response);
      	    return;
      	}
      	
      	//权限校验
      	if(!checkAuthority()) {
      	    writeFailure(response);
      	    return;
      	}
      	
        chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}
	
	/**权限校验*/
	private boolean checkAuthority() {
	    //TODO 这里进行权限检查
		
	    return true;
	}
	
	/**校验失败返回*/
	private void writeFailure(HttpServletResponse response) {
		// 让浏览器用utf8来解析返回的数据
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		// 告诉servlet用UTF-8转码,而不是用默认的ISO8859
		response.setCharacterEncoding("UTF-8");
		JSONObject result = new JSONObject();
		result.put("status", "error");
		result.put("message", "对不起,你没有权限!");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.write(result.toJSONString());
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

 

你可能感兴趣的:(Java,spring,boot)