CORS解決跨域問題的幾種方法


一 后端服務器使用過濾器

新建過濾器:

/**
 * 解決跨域
 */
public class AccessControlAllowOriginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("解決跨域請求");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");//允許所有網站跨域訪問
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
//這里如果前端請求header首字母是小寫也是不行得,所以大小寫都寫上就沒問題了 response.setHeader(
"Access-Control-Allow-Headers", "access-control-allow-origin,content-type,x-requested-with,Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With"); filterChain.doFilter(servletRequest, response); } @Override public void destroy() {} }

前端header需要添加:

$.ajax( {
            url : 'http://c2.zhuzher.com/pdm/know/active?hotelid=808047&sdate=2019-11-09&edate=2019-11-11',
            beforeSend: function (xhr) {
                    xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //設置跨域訪問信息
                    xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
            },
            type : 'get',
            dataType : 'json',
            data:{},
            success : function(data) {
                alert(1111);
            }
        });

二 后端接口springboot/springmvc使用注解

springMVC的版本要在4.2或以上版本才支持@CrossOrigin ;

方法需要指明Get或者POST才行:

 

 

三 本地nginx反向代理(推薦)

本地下載解壓nginx,添加一個server配置文件:

注意,如果是放在nginx的html目錄下一般是不需要加跨域配置的,否則會報配置多余錯誤

每次可先直接使用試試,不行再加下面add_header等配置.

    ###start跨域支持配置####
    add_header Access-Control-Allow-Origin '*';
    add_header Access-Control-Allow-Headers Accept,Origin,X-Requested-With,Content-Type,If-Modified-Since,Last-Modified,Content-Length,Content-Range,Range,Content-Description,Content-Disposition;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    add_header Access-Control-Request-Headers Content-Disposition;
    add_header Access-Control-Allow-Credentials true;

    ###end ###

    server {
        listen       80;
        server_name  127.0.0.1;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        
        #自定義本地路徑,代理轉發請求
        location /pdm        {
            proxy_pass   http://c2.zhuzher.com/pdm;
       }

    }
    
    server {
        listen       8081;
        server_name  127.0.0.1;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        
        #自定義本地路徑,代理轉發請求
          location /pdm        {
            proxy_pass http://c2.zhuzher.com/pdm;
            charset  utf-8;
            #   proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;        
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    }

注意

項目里面直接調用配置的8081端口就可以了:

api.get('//localhost:8081/pdm/user/login',data)

注意這里還有一點需要注意,如果Content-Type是 application/json的話是無法發送跨域請求的,這里提供一種解決辦法,就是接口前端請求type改成
'Content-Type':'text/plain'
發送數據轉成字符串:
JSON.stringify(data)

后端接口用String接受數據,然后再轉成對象就可以了:
 @PostMapping("/distributeBatch")
    public ResMsg distributeSaleBatch(@RequestBody String params){
        System.out.println(params);
        //Integer user_id, Integer customer_id
        //Gson 字符串轉對象
        List<Map<String, Integer>> fromJson = new Gson().fromJson(params, new TypeToken<List<Map<String, Integer>>>() {
        }.getType());
        System.out.println(new Gson().toJson(fromJson));
        return registeredCustomerService.distributeSaleBatch(fromJson);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM