springboot的@CrossOrigin注解解决细粒度的配置跨域
1、请求Controller
import java.util.HashMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
@CrossOrigin(origins = "http://172.16.71.27:8080")
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
2、js请求
<script>
$(function() {
$('#title').click(function() {
// alert('点击了');
$.ajax({
url : "http://localhost:8081/api/get",
type : "POST",
data : {
name : "测试"
},
success : function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});
});
})
</script>