跨域请求阻止春天REST服务+ AJAX [英] Cross-Origin Request Blocked Spring REST service + AJAX
问题描述
无法调用春REST服务
Unable to call spring REST service
我的春季服务
@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 code
My AJAX code
$.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');
}
});
我收到以下错误:(
I am getting following error :(
跨域请求阻止:同源策略不允许在读 HTTP远程资源://本地主机:8080 /用SpringMVC / REST / MAS /验证。这可以固定通过移动资源到相同域或启用CORS
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/SpringMVC/rest/MAS/authenticate. This can be fixed by moving the resource to the same domain or enabling CORS.
我也尝试过数据类型:JSONP
。其追加我的身体的对象为URL这使得不同的URL,不能打我的服务URL,然后,得到了404错误。
i have also tried dataType: "jsonp"
. its append my body object into URL which make different URL and cannot hit my service URL then and got 404 error.
我的浏览器:火狐36.0.4
My browser: firefox 36.0.4
我怎么能得到这个错误摆脱,任何帮助?
How i can get rid from this error, any help?
推荐答案
我的AJAX调用和服务都行。搜索了很多在互联网上后,我发现它的服务器端的问题不是客户端。
My AJAX call and service were OK. After searching a lot on internet i have found that its server side problem not client side.
在使用Spring服务器端,我们必须实施过滤器,这将使CORS请求。
on server side with Spring we have to implement filter which will allow CORS requests.
过滤器会是这样的。
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private static final Log LOG = LogFactory.getLog(CORSFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOG.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
和在web.xml中应用此过滤器的服务请求像这样
and in web.xml apply this filter on your service requests like this
<filter>
<filter-name>cors</filter-name>
<filter-class>com.test.common.controller.CORSFilter</filter-class> <!-- your package name and filter class -->
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这可以帮助别人谁通过这个问题去了。 :)
This may help someone else who went through this problem. :)
这篇关于跨域请求阻止春天REST服务+ AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!