跨域,就是从不同的的IP端口获取数据,比如说,从www.baidu.com获取数据,就叫跨域!那么localhost:8080与localhost:8081之间呢?也叫跨域。如果处理的不好,就会报错,不仅前端报错,后端也会报错。
那么在SpringBoot中如何解决跨域问题,如下:
1、编写一个支持跨域请求的 Configuration
package com.wangru.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 处理AJAX请求跨域的问题
* @author wangru
* @time 2018-07-13
*/
@Configuration
public class CrossDomain extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowCredentials(false).maxAge(3600);
}
}
2、http请求接口
package com.wangru.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloWorldController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "Hello World ! Hello SpringBoot !";
}
@RequestMapping(value = "/data", method = RequestMethod.GET)
@ResponseBody
public String data() {
return "This is My data ! ";
}
}
3、前端请求页面
<!DOCTYPE html>
<head>
<meta charset="gbk">
<title>springBoot</title>
</head>
<body>
<div id="main" style="height:600px"></div>
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$.ajax({
async : false ,
type : "get",
url:"http://192.168.1.102:8081/hello",
data : {
},
dataType : "jsoup",
success:function(result){
alert(result);
}
});
</script>
</body>