springboot+vue+shiro Ajax跨域问题解决方法

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//自定义filter,可通过@WebFilter或者在@Configuration注解的配置类中用@Bean注解实例化
public class CrossFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //跨域解决获取前端Origin
        String origin = request.getHeader("Origin");
        //如果Origin不为空,xxx.com开头
        //  if (StringUtils.isNotBlank(origin) && origin.indexOf("xxx.com") != -1) {
        //设置跨域请求头
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Request-Headers", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, Accept, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
        response.addHeader("Access-Control-Max-Age", "3600");
        //}
        //ajax 提交json数据(比如服务端@RequestBody注解的入参)提交需要加此段代码,放过第一次的OPTIONS请求,否则依然会跨域,建议都加
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(200);
            return;
        }
        //继续向后执行
        chain.doFilter(request, response);
    }
}
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean corsFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new CorsFilter());
        filterRegistrationBean.addUrlPatterns("/*");//配置过滤规则
        filterRegistrationBean.setName("corsFilter");//设置过滤器名称
        filterRegistrationBean.setOrder(1);//执行次序,数字越大,优先级越低
        return filterRegistrationBean;
    }

Access to XMLHttpRequest at 'http://xxx.yyy.com/queryPage' from origin 'http://zzz.yyy.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值