Java后端解决跨域问题

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.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 跨域过滤器
 * @author kong
 *
 */

/**
 * 跨域过滤器
 * @author kong
 *
 */
@Component
public class CorsFilter implements Filter ,Ordered{

    static final String OPTIONS = "OPTIONS";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String origin = request.getHeader("Origin");    // 获得客户端domain
        if(origin == null) {
            origin = request.getHeader("Referer");
        }
        response.setHeader("Access-Control-Allow-Origin", origin);            // 允许指定域访问跨域资源
        response.setHeader("Access-Control-Allow-Credentials", "true");       // 允许客户端携带跨域cookie,此时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,satoken");	// 允许的header参数
//        response.setHeader("Access-Control-Allow-Headers", "*");  // 允许的header参数

        // 如果是预检请求,直接返回
        if(OPTIONS.equals(request.getMethod())) {
            System.out.println("=======================浏览器发来了OPTIONS预检请求==========");
            response.getWriter().print("");
            return;
        }

        //System.out.println("*********************************过滤器被使用**************************2233");
        chain.doFilter(req, res);
    }
    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

注意:如果项目中注入了

WebMvcConfigurationSupport类,则会失效。可以将
WebMvcConfigurationSupport改为实现
WebMvcConfigurer。

如果不生效,请确认是否真的是跨域问题:F12-console是否出现了跨域提示。Java后端解决跨域问题_第1张图片

用postman试一下接口是否能通。

服务器重启->浏览器清缓存->浏览器重启。

是否传了非允许的请求头参数Java后端解决跨域问题_第2张图片

 

你可能感兴趣的:(linux,运维,服务器)