昨天尝试一下前后端分离,用SpringMVC写了个Restfulapi,在本地服务器部署,然后新建了一个新工程写前端界面获取数据,结果在用jquery的ajax获取api接口的数据,出现了跨域问题,提示:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
一开始搜索到了一个解决方案,即设置ResponseHeader,在Controller处加入response.setHeader(“Access-Control-Allow-Origin”,"*");
@RequestMapping(value = "/queryweatheryearRestful",method = RequestMethod.GET) @ResponseBody public List<Weather> queryweatheryearRestful(HttpServletResponse response){ response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Cache-Control","no-cache"); List<Weather> waetheryear=weatherService.queryWeatherYear(); return waetheryear; }最后发现有更简单的方法,如果是SpringMVC4.2以上的版本,在方法上加上注解@CrossOrigin即可解决跨域问题,controller的代码如下:
@RequestMapping(value = "/queryweatheryearRestful",method = RequestMethod.GET) @ResponseBody @CrossOrigin public List<Weather> queryweatheryearRestful(){ List<Weather> waetheryear=weatherService.queryWeatherYear(); return waetheryear; }