java spring后台如何解决跨域请求 No 'Access-Control-Allow-Origin' header is present on the requested resource

下一篇:很抱歉没有了

在别的网站上通过aja访问后台网站出现不能跨域请求的问题,出现如下错误

XMLHttpRequest cannot load http://localhost:8080/getname. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

出现上述错误就是需要解决跨域问题

一般有两种解决方法

1.是 后台返回的数据格式改成jsonp的形式

2.后台response添加header,response.setHeader("Access-Control-Allow-Origin", "*");

"Access-Control-Allow-Origin", "*" 表示所有网站都可以访问

或者可以指定某个具体域名访问response.setHeader("Access-Control-Allow-Origin", "http://baidu.com");

代码实例如下:

@Controller
public static class TestAjaxController {

	@RequestMapping(value = "/test")
	@ResponseBody
	public String getLoactionInfo(String userId, HttpServletResponse response)
			throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		//.......
		return ".....";
	}
}

3.或者通过修改服务器上apache配置来解决,参考资料 http://www.jsjtt.com/xitongyingyong/Apache;Nginx/2013-10-30/29.html

来源://作者:/更新时间:2016-04-13
相关文章
评论:
验证码:
匿名评论: