【正经贴】解决get,post请求跨域问题

get 请求解决方案:jsonp
前端请求:

function queryTrouble(typeId){
    $.ajax({
        type: "GET",
        url: "https://xxx.com/v1/trouble/getTroubles",
        data: {typeId:typeId},
        xhrFields:{widthCredentials:true},
        dataType: "jsonp",
        cache:true,
        jsonpCallback: "Troublemycallback",
        success: function (data) {
            if(data.code==200){  
               alert("success");
            }
        }
    });
}

后端接收:

    @GetMapping(value = "getTroubles")
    public String getTroubles(int typeId, HttpServletRequest req){
        String callback = req.getParameter("callback");
        List lists = null; //走缓存 删减
        try {
            if(lists == null){
                lists = repairsTroubleService.getTroubles(typeId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.responseCORS(new Rsp(ResultStatus.error_search_failed),callback);
        }
        return ResponseUtils.responseCORS(new Rsp(lists),callback);
    }
public class ResponseUtils {


    public static String responseCORS(Object obj,String callback){
        return callback+"("+JSON.toJSONString(obj)+")";
    }
}

post跨域解决方案:xhr

前端请求:

function postSubmit(){
     var submitData = 'orderPlatform=1&brandId='+$("#Jbrand .needPost").data("brandid")+'&brandName='+$("#Jbrand .needPost").data("brandname")+'&typeId='+$("#Jbrand .needPost").data("typeid")+'&typeName='+$("#Jbrand .needPost").data("typename")+'&troubleName='+$("#Jtrouble .needPost").html()+'&color='+$("#Jcolor .needPost").html()+'&orderType='+$("#JrepireMode .needPost").data("mode")+'&orderStation='+$("#JrepairBranch .info p").html().replace("
"," ")+'&customer='+$("#JuserInfo .needPost[name=cusname]").val()+'&telephone='+$("#JuserInfo .needPost[name=mobile]").val()+'&address='+$("#Jaddress .seled").html()+$("#Jaddress .needPost[name=address]").val()+'&comments='+$(".item textarea[name=memo]").val()+'&price='+$("#Jtrouble .iptSelBox .cur").data("price"); submitData = urlParamToJson(decodeURIComponent(submitData.replace(/\+/g," "),true)); postCORS({ url: "https://xxx.com/v1/order/add", data: submitData, init: function (data, xhr) { if (xhr) { xhr.withCredentials = true } }, callback: function (data) { eval('var result=' + data); if ( result.code == 200 ) { location.href = "//xxx.com/success/index.html" } else { alert(JSON.stringify(result)); } ifSubmit = false; } }); } function urlParamToJson(data_){ var params = data_.split('&'), json = new Object(), param; for(var i = 0; i < params.length; i++){ param = params[i].split('='); json[param[0]] = param[1]; } return json; } function postCORS(b) { var e = createCORSRequest(); if (!e) { b.init && b.init(b.data, e); var d = new Transfer({ url: b.url, data: b.data, callback: function(f) { b.callback(f, { isXhr: false }) } }); d.send() } else { e.open("POST", b.url); b.init && b.init(b.data, e); e.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); e.onreadystatechange = function() { var f = { isXhr: true }; if (e.readyState == 4) { if (e.status == 200 || e.status == 304) { f.status = "success"; b.callback(e.responseText, f) } else { f.status = "error"; b.callback(e, f) } } }; var a = []; for (var c in b.data) { if (b.data.hasOwnProperty(c)) { a.push(encodeURIComponent(c) + "=" + encodeURIComponent(b.data[c])) } } e.send(a.join("&")) } } function createCORSRequest() { var b; try { b = new XMLHttpRequest(); if (! ("withCredentials" in b)) { b = null } } catch(a) { b = null } return b } function Transfer(a) { this.url = a.url; this.callback = a.callback; this.params = a.data; a.options = a.options || {}; var b = { localProxy: "/favicon.ico", defaultName: "cross.default.name" }; this.options = this.extend(b, a.options); this.init() } Transfer.prototype = { init: function() { function a(h, f) { var g = null; try { g = document.createElement("<" + h + ' name="' + f + '">') } catch(i) {} if (!g || g.nodeName != h.toUpperCase()) { g = document.createElement(h); g.name = f } return g } this.params.windowname = 1; this.files = this.options.files || []; delete this.options.files; var b = "transfer_" + new Date().getTime(); this.options.defaultName = b; var d = a("iframe", b); d.name = b; d.style.display = "none"; d.style.position = "fixed"; d.style.top = d.style.left = "-10000px"; document.body.appendChild(d); var c = document.createElement("form"); c.style.display = "none"; c.target = b; c.action = this.url; c.method = "post"; c.encoding = c.enctype = "application/x-www-form-urlencoded"; document.body.appendChild(c); this.frame = d; this.form = c; this.state = 1; this._setRequest() }, _setRequest: function() { var j = this, c = j.frame, a = j.form, k = j.options, i = k.localProxy; if (c.onreadystatechange !== undefined) { c.onreadystatechange = h } else { c.onload = h } function b() { var l; try { l = c.contentWindow.name } catch(m) { l = k.defaultName } if (l == k.defaultName) { l = '{"error": 1}' } j.callback(l) } function f() { var m = false; try { m = c.contentWindow.location.host == location.host } catch(l) {} return m } function g() { clearTimeout(d); c.onreadystatechange = c.onload = null; c.parentNode.removeChild(c); a.parentNode.removeChild(a); c = null; a = null; for (var l in j) { if (j.hasOwnProperty(l)) { j[l] = null; delete j[l] } } } var e = false; var d; function h() { try { if (c.contentWindow.location.href == "about:blank") { return } } catch(l) {} if (j.state == 3) { if (!f() && !e) { e = true; c.contentWindow.location = i } else { if (c.readyState && !(/complete|loaded/i.test(c.readyState))) { return } b(); g() } } if (j.state == 2) { j.state = 3; c.contentWindow.location = i } if (!d) { d = setTimeout(function() { b(); g() }, 120000) } } }, send: function() { var e = this.params, b = this.form, h, j; var c = Object.prototype.toString; for (h in e) { if (e.hasOwnProperty(h)) { j = e[h]; if (c.call(j) === "[object Array]") { var a = h + "[]"; for (var f = 0, d = j.length; f < d; f++) { b.appendChild(g(a, j[f])) } } else { b.appendChild(g(h, j)) } } } this.state = 2; b.submit(); function g(k, l) { var i = document.createElement("input"); i.name = k; i.value = l; return i } }, isObject: function(a) { return Object.prototype.toString.call(a) == "[object Object]" && !a.nodeType }, isArray: function(a) { return Object.prototype.toString.call(a) == "[object Array]" }, extend: function(c, b) { var d = this.clone(b); var a; for (a in d) { if (d.hasOwnProperty(a)) { c[a] = d[a] } } return c }, clone: function(f) { var c = this, d; if (c.isArray(f)) { d = []; for (var e = 0, a = f.length; e < a; e++) { d.push(c.clone(f[e])) } } else { if (c.isObject(f)) { d = {}; for (var b in f) { if (f.hasOwnProperty(b)) { d[b] = c.clone(f[b]) } } } else { d = f } } return d } };

后端接收:


    @RequestMapping(value = "add",method = RequestMethod.POST)
    public void add(RepairsOrder repairsOrder, HttpServletResponse resp,HttpServletRequest req) throws Exception {
        // 封装数据格式
        JSONObject result = new JSONObject();
        try {
            if(repairsOrder.getOrderPlatform() != null){
                repairsOrderService.add(repairsOrder);
                result.put("code", 200);
                result.put("data", "success");
            }else{
                result.put("code", 500);
                result.put("data", "failure");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("data", "failure");
        }

        // 指定编码
        resp.setContentType("text/json");
        resp.setCharacterEncoding("UTF-8");
        // 跨域处理
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");

        if(req.getHeader("Origin") != null){
            resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        }else{
            resp.setHeader("Access-Control-Allow-Origin", "*");
        }
        // 写入数据
        resp.getWriter().print(result);
        resp.flushBuffer();
    }

post跨域解决方案:ajax

前端请求:

function ajaxPost(){
    /*两种param都可以*/
     var param = "orderPlatform=1&brandId=1&brandName=发&typeId=1&typeName=C199&troubleName=坏&color=灰色&orderType=1&orderStation=大厦7楼705号&customer=小&telephone=&address=409&comments=备注&price=190";
   /* var param = {
	        orderPlatform:1,
	        brandId:1,
	        brandName:'发',
	        typeId:1,
	        typeName:'C199',
	        troubleName:'坏',
	        color:'灰色',
	        orderType:1,
	        orderStation:'大厦7楼705号',
	        customer:'小',
	        telephone:'',
	        address:'409',
	        comments:'备注',
	        price:190
	    } */

    $.ajax({
	        type: "POST",
	        url: "https://xxx.com/v1/order/add",
	        data: param,
	        success: function (res) {
	            if(res.code==200){
	            	alert("成功!");
	            }
	        },
	        error:function(res){
	            alert(res);
	        }
	    });
}

后端接收代码同上。

post跨域失败案例:ajax
前端不能指定contentType类型为json,后端接收参数不能使用@RequestBody

post会请求前会发送一次OPTIONS预请求按下面的例子是不会通过的

error:

前端代码:

 $.ajax({
	        type: "POST",
	        url: "https://xxx.vom/v1/order/add",
	        data: JSON.stringify(param),
			contentType: "application/json;charset=UTF-8",
	        success: function (res) {
	            if(res.code==200){
	            	alert("成功!");
	            }
	        },
	        error:function(res){
	            alert(res);
	        }
	    });

后端代码:


    @RequestMapping(value = "add",method = RequestMethod.POST)
    public void add(@RequestBodyRepairsOrder repairsOrder, HttpServletResponse resp,HttpServletRequest req) throws Exception {
        // 封装数据格式
        JSONObject result = new JSONObject();
        try {
            if(repairsOrder.getOrderPlatform() != null){
                repairsOrderService.add(repairsOrder);
                result.put("code", 200);
                result.put("data", "success");
            }else{
                result.put("code", 500);
                result.put("data", "failure");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("data", "failure");
        }

        // 指定编码
        resp.setContentType("text/json");
        resp.setCharacterEncoding("UTF-8");
        // 跨域处理
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");

        if(req.getHeader("Origin") != null){
            resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        }else{
            resp.setHeader("Access-Control-Allow-Origin", "*");
        }
        // 写入数据
        resp.getWriter().print(result);
        resp.flushBuffer();
    }

 

你可能感兴趣的:(请求跨域,GET,POST,跨域解决方案)