【发布时间】:2015-06-05 23:54:26
【问题描述】:
无法调用spring REST服务
我的春季服务
@RequestMapping(value = "/MAS/authenticate", method = RequestMethod.POST)
public ResponseEntity<Map<String, String>> authenticate(@RequestBody Subject subject) {
Map<String, String> result = new HashMap<String, String>();
result.put("result_detail", "Invalid Password");
result.put("result", "failure");
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
responseHeaders.add("Access-Control-Allow-Origin", "*"); // also added header to allow cross domain request for any domain
return new ResponseEntity<Map<String, String>>(result, responseHeaders, HttpStatus.OK);
}
我的 AJAX 代码
$.ajax(
{
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "http://localhost:8080/SpringMVC/rest/MAS/authenticate",
headers: {"Access-Control-Allow-Origin" : "*"},
data:{},
dataType: "json", //also tried "jsonp"
success: function(data, status, jqXHR)
{
alert('success');
},
error: function(jqXHR, status)
{
alert('error');
}
});
我收到以下错误:(
跨域请求被阻止:同源策略不允许读取位于http://localhost:8080/SpringMVC/rest/MAS/authenticate 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。
我也试过dataType: "jsonp"。它将我的正文对象附加到 URL 中,该 URL 生成不同的 URL,然后无法访问我的服务 URL 并得到 404 错误。
我的浏览器:firefox 36.0.4
我怎样才能摆脱这个错误,有什么帮助吗?
【问题讨论】:
-
你使用的是哪个服务器?
-
@Halayem Anis:我正在使用 webSphere,但也在 tomcat 上尝试过。两者都出现相同的错误
标签: java javascript html ajax spring