zoukankan      html  css  js  c++  java
  • springboot跨域解决

    package com.xf.config;
    
    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.annotation.WebFilter;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author admin 跨域过滤器
     */
    @WebFilter(urlPatterns = "/*", filterName = "corsFilter")
    public class CorsFilter implements Filter {
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) rep;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            // response.setHeader("Access-Control-Allow-Methods", "POST, GET,
            // OPTIONS, DELETE");
            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",
                    "Content-Type, Access-Control-Allow-Headers, Authorization,X-Requested-With,openid,formId");
            chain.doFilter(req, response);
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    
    }

    NG添加配置:

        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';

    在控制台测试:

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://xxxxxxxx);
    xhr.send(null);
    xhr.onload = function(e) {
        var xhr = e.target;
        console.log(xhr.responseText);
    }

    能打印出结果就是成功了哦!另:option请求建议直接在nginx处理掉。

    if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
            #支持put和delete请求
        return 200;
    }

    有追求,才有动力!

    向每一个软件工程师致敬!

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    全面提价2499元起小米6发布:四曲陶瓷机身+骁龙835+变焦双摄(小米在设计上也多次获得红点最佳、iF金奖等72项工业设计大奖)
    VCL的通用属性,方法和事件 good
    抗日名将粟裕
    部署 Redis 群集
    Xamarin
    NET Core控制反转(IoC)
    C#开发Linux守护进程
    数据一致性(consistency)、服务可用性(availability)、分区容错性(partition-tolerance)
    ssm框架
    javascript面向对象之闭包
  • 原文地址:https://www.cnblogs.com/wujf/p/15060983.html
Copyright © 2011-2022 走看看