1. 程式人生 > >ajax跨域post請求

ajax跨域post請求

為什麼會出現跨域問題?

首先我們要先了解一個概念--同源策略。同源策略,它是由Netscape提出的一個著名的安全策略。現在所有支援JavaScript 的瀏覽器都會使用這個策略。所謂同源是指,域名,協議,埠相同。目的是出於安全考慮,防止js指令碼隨意呼叫其他網站的資源。

一.跨域請求,不需jsonp的post跨域請求(Springboot)

問題描述

先把前後臺的程式碼貼出來

後臺controller

//query all user     @ResponseBody     @RequestMapping(value = "/getAllUser",method= RequestMethod.POST)     public List<User> getAllUser(@RequestBody Map<String,Object> reqMap){         return userService.findAllUser(reqMap);     }

前臺js

$.ajax({

url:'http://localhost:8080/user/getAllUser',

data:{pageNum:3, pageSize:3},

type:'post',

dataType:'json',

contentType: "application/json",

success:function(data){

alert("success");

console.log(data);

},

error:function(reason){

console.log(reason)

}

});

顯示如下錯誤,經查詢後發現是跨域導致的錯誤

後臺改進

在Application啟動類中註冊WebMvcConfigurer

@Bean

public WebMvcConfigurer webMvcConfigurer() {

return new WebMvcConfigurerAdapter() {

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/**").allowedOrigins("*");

}

};

}

重新啟動專案後瀏覽器報400錯誤

  

經過研究後發現是Json格式錯誤,ajax請求的是json格式,但是ajax傳送過去的引數顯然不是json格式,所以我們還需要將引數格式化為json格式然後傳到後臺。使用JOSN.stringify方法

改正後的後臺程式碼

$.ajax({

url:'http://localhost:8080/user/getAllUser',

data:JSON.stringify({pageNum:3, pageSize:3}),

type:'post',

dataType:'json',

contentType: "application/json",

success:function(data){

alert("success");

console.log(data);

},

error:function(reason){

console.log(reason)

}

});

再次重新整理頁面

二.跨域請求,需jsonp的post跨域請求

ajax的post請求如何讓web或介面的方法支援跨域()

只是方法,如果是伺服器或者整個web,找其他資料
只需要加入
response.setHeader("Access-Control-Allow-Origin", "*");
即可

@ResponseBody

@RequestMapping(value="login1", method=RequestMethod.GET, produces="application/json;charset=UTF-8")

public String login1(HttpServletRequest request,HttpServletResponse response) throws Exception{

response.setHeader("Access-Control-Allow-Origin", "*");

@ResponseBody

@RequestMapping(value="login", method=RequestMethod.POST, produces="application/json;charset=UTF-8")

public String login(@RequestBody String requestJson,HttpServletRequest request,HttpServletResponse response) throws Exception{

//設定跨域請求

response.setHeader("Access-Control-Allow-Origin", "*");

通過瀏覽器請求get

獲取通過360瀏覽器的console請求post

var data={

thirdType:3,

openId:"a970a9778",

userName:"22288",

headImage:"http://www.baidu.com/image.png"

}

$.ajax({

type:"POST",

dataType:"json",

url:"http://192.168.1.5:8080/ryqp/login.shtml",

data:data,

success: function(msg){

if(msg.code == "APP.000"){

alert('刪除成功');

}else {

alert("刪除失敗!");

}

},

error: function (msg) {

alert("刪除失敗!");

}

});