CORS与chrome中的Angular 2不兼容

时间:2017-07-31 05:08:24

标签: javascript angular soap cors

我正在使用javascript代码调用部署在weblogic上的soap webservice,并使用jaxws在java中开发。从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

我还设置了如下的请求标头:

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上调用我的webservices的代码片段

    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;

1 个答案:

答案 0 :(得分:2)

在您的服务中创建此类:

@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");
    }
}