幾天前,我實現了一個web服務(客戶端均爲&服務器)。客戶發送請求XMLHttpRequest()
,這很好。然而,今天我試圖改變它的發送請求到jquery的$ .ajax();辦法。從javascript web-service客戶端發送CORS POST請求返回http 405錯誤
爲此,在這裏,這是我的客戶端功能:
function ajaxQuery(){
$.ajax({
url: 'http://localhost:8080/recommender/sider/drugs',
method:'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({"uris":["SampleName1", "SampleName2", "SampleName3"],"limit":100 }),
xhrFields: {
withCredentials: true
}
}).done(function(data) { console.log(data) });
}
這是我在服務器端使用的過濾器:
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
HttpServletResponse alteredResponse = ((HttpServletResponse) response);
addCorsHeader((HttpServletRequest) request, alteredResponse);
}
filterChain.doFilter(request, response);
}
private void addCorsHeader(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Requested-By");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Max-Age", "1728000");
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
可惜的是,當我發這個帖子的請求我得到了http 405錯誤,這是我錯誤部分的截圖。 https://www.dropbox.com/s/3wqlqkbnqwnjllx/Screenshot%202015-08-18%2011.27.29.png?dl=0
我該怎麼處理這個問題?
是的,現在可以正常運行。 – zwlayer