我正在使用 javascript 代码调用部署在 weblogic 上并使用 jaxws 在 java 中开发的 soap webservice。从 IE11 我收到来自 SOAP 的响应,但从 chrome 我收到以下错误:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access.
The response had HTTP status code 405.
我在 chrome 中添加了 cors 扩展,然后出现以下新错误:
Response for preflight has invalid HTTP status code 405
我还设置了如下请求 header :
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'X-Custom-Header');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE');
还是没有成功。
下面是我的代码片段,用于调用部署在 weblogic 上的 web 服务
var soapMessage = this.createSOAPMessage();
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else {
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('POST','http://IPAddress:7001/Path/ServiceImplService?WSDL');
if(!xhr){
console.log('XHR Issue');
return;
}
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'X-Custom-Header');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE');
xhr.send(soapMessage);
var result
xhr.onload = function(){
result = xhr.responseText;
console.log('===Result====> '+result);
}
return result;
最佳答案
在您的服务中创建此类:
@Provider
@PreMatching
public class CorsFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestCtx, ContainerResponseContext responseCtx) throws IOException {
responseCtx.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseCtx.getHeaders().add("Access-Control-Allow-Origin", "*");
responseCtx.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseCtx.getHeaders().add("Access-Control-Allow-Methods", "GET, POST");
}
}
关于javascript - CORS 不适用于 chrome 中的 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407863/