Spring Boot + AngularJS 前端AngularJS发送get,post请求实现跨域请求
后端SpringBoot服务设置
新建类CorsConfiguration
@Configuration
public class CorsConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println(“CorsConfiguration…”);
registry.addMapping("/") //允许跨域访问的链接 "/" 表示允许所有链接
.allowedMethods(""); //允许的http方法(GET,PUT,POST,DELETE…),"“表示允许所有方法
}
}
controller层
/**
* 返回全部列表
* @return
/
@RequestMapping("/findAll")
public List findAll(){
return informService.findAll();
}
/*
* 增加
* @param inform
* @return
*/
@RequestMapping(”/add")
public Result add(@RequestBody Inform inform){
try {informService.add(inform);return new Result(true, "增加成功");} catch (Exception e) {e.printStackTrace();return new Result(false, "增加失败");}}
前端AngularJS
//读取列表数据绑定到表单中
this.findAll=function(){
// return $http.jsonp(‘http://localhost:8080/inform/findAll’);
return $http.get(‘http://localhost:8080/inform/findAll’);
}
//增加
this.add=function(entity){
return $http.post(‘http://localhost:8080/inform/add’,entity,{
headers : {‘Content-Type’:‘application/json’}
});
}
PS:在发送post请求的时候一定要设置Headers (headers : {‘Content-Type’:‘application/json’})为application/json。
新人路过,不喜勿喷,欢迎提出宝贵意见。
如果觉得《Spring Boot + AngularJS 前端AngularJS发送get post请求实现跨域请求》对你有帮助,请点赞、收藏,并留下你的观点哦!