前端页面调用spring mvc接口发生跨域问题解决方案
使用spring mvc开发了一个Restful接口供前端调用
@GetMapping("/hello")
ResponseEntity<?> hello() {
Map<String, Object> resMap = new HashMap<>();
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("{").append('"').append("key").append('"').append(":").append('"').append(123).append('"').append("}");
sb.append("]");
resMap.put("returnInfo", sb.toString());
return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.OK);
}
前端调用如下:
<Button type="primary" onClick={function () {
fetch("http://localhost:8080/hello").then(data=>{
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取和后台返回的数据
return data.text();
}).then(ret=>{
// 注意这里得到的才是最终的数据
console.log(ret);
})
}}>Primary Button</Button>
但是页面报错,F12后错误提示如下:

判断应该是跨域问题,百度后发现spring mvc已经有很好的解决方案,添加@CrossOrigin即可。
@CrossOrigin @GetMapping("/hello") ResponseEntity<?> hello() { Map<String, Object> resMap = new HashMap<>(); StringBuilder sb = new StringBuilder(); sb.append("["); sb.append("{").append('"').append("key").append('"').append(":").append('"').append(123).append('"').append("}"); sb.append("]"); resMap.put("returnInfo", sb.toString()); return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.OK); }
接口调用成功

参考链接:https://segmentfault.com/a/1190000011174645
越努力越幸运!

浙公网安备 33010602011771号