Spring boot 1.5
使用@CrossOrigin
单个接口跨域直接在方法上添加@CrossOrigin,也可以在controller上添加注解
//@CrossOrigin
@RestController
@RequestMapping(“smsapp/sendmsg”)
public class SendMsgController {
@CrossOrigin
@PostMapping("/sendpostyzm")
public JSONObject sendyzm(@RequestBody JSONObject requestJson) {
String phone= requestJson.getString(“phone”);
…
}
ajax
$.ajax({
type: “POST”,
url: “http://XXXXXXX.com/smsapp/sendmsg/sendpostyzm”,
//dataType:“json”,
contentType:“application/json”,
data :JSON.stringify({“phone” : $(’#tel’).val()}),
success : function(data) {
alert(data.code)
}
});
Springboot2.0及以上版本添加 @CrossOrigin还无法跨域是因为Spring5里面对这个注解改动了
@CrossOrigin源码查看
*
By default this is not set in which case the
**** {@code Access-Control-Allow-Credentials} header is also not set and
* credentials are therefore not allowed.***
*/
String allowCredentials() default “”;
所以需要手动添加如下
@CrossOrigin(allowCredentials=“true”,maxAge = 3600)
@PostMapping("/sendpostyzm")
public JSONObject sendyzm(@RequestBody JSONObject requestJson) {
String phone= requestJson.getString(“phone”);
。。。。。
}
或者在ajax请求中添加
$.ajax({
type: “POST”,
url: “http://XXXXX.com/smsapp/sendmsg/sendpostyzm”,
xhrFields: {
withCredentials: true // 设置运行跨域操作
},
//dataType:“json”,
contentType:“application/json”,
data :JSON.stringify({“phone” : $(’#tel’).val()}),
success : function(data) {
alert(data.code)
}
});