2

Related to this question Convert curl-command to php curl I'm trying to convert a curl-statement to an ajax request.

My request is working with the following curl-command:

curl --user XXXX:YYYY "URL"

But trying to use it in jquery ajax it is not working, where my code looks like:

$.ajax({
    url : "URL",
    type : 'GET',
    dataType : 'json',
    contentType : 'application/json',
    username: "XXXX",
    password: "YYYY",
    success : function(data) {
        console.log(JSON.stringify(data));
    },
    error : function() {
        console.log("Cannot get data");
    }
});

I also tried to set a beforeSend value, shown below:

$.ajax({
    url : "URL",
    type : "GET",
    processData: false,
    dataType : 'json',
    headers : {
        'Accept' : 'application/json',
        'Content-Type' : 'application/json'
    },
    data : JSON.stringify(text),
    withCredentials : true,
    beforeSend : function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + btoa("XXXX:YYYY"));
    }
}).then(function(data) {
    console.log('data', data);
}, function(err) {
    console.log('err', err);
});

In both cases I get the same error:

XMLHttpRequest cannot load "URL". Response for preflight has invalid HTTP status code 401

Does anyone knows how to fix this?

UPDATE

The headers look like this:

General

Request URL: "URL"
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:***

Response Headers

Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Connection:Keep-Alive
Content-Language:en
Content-Length:1061
Content-Type:text/html;charset=utf-8
Date:Wed, 10 Feb 2016 13:12:34 GMT
Expires:0
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache
Set-Cookie:JSESSIONID=CE27E7E84651D519BD99802B65C431EB; Path=/matchbox-webservice/; Secure
Strict-Transport-Security:max-age=31536000 ; includeSubDomains
WWW-Authenticate:Basic realm="Realm"
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

Request Headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,pt;q=0.2,nb;q=0.2,da;q=0.2
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:***
Origin:http://evil.com/
Pragma:no-cache
Referer:http://localhost:8080/templates/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36
Community
  • 1
  • 1
fsulser
  • 853
  • 2
  • 10
  • 34
  • Well, a 401 indicates that the server refuses to reply due to authorization issues. Note: _not_ authentication, but authorization. Are you really sure that is a legitim request to the server? – arkascha Feb 10 '16 at 13:05
  • If the preflight is failing it sounds like the receiving domain does not support CORS, which means that you cannot make the request from JS. – Rory McCrossan Feb 10 '16 at 13:05
  • If CORS is not supported wouldn't the curl-command fail? – fsulser Feb 10 '16 at 13:07
  • cURL is not restricted by CORS and wouldn't send a preflight. Those are sent by browsers. Not all API's are accessible using XmlHttpRequest. – charlietfl Feb 10 '16 at 13:11
  • 1
    @fsulser no it wouldnt. Curl does not performn any checks regarding CORS. Browsers check for CORS headers. You could try checking developer console in your browser to get all the headers that your ajax call is sending – Lauri Orgla Feb 10 '16 at 13:11
  • 1
    @fsulser — http://stackoverflow.com/a/25763329/19068 — On why cURL is not restricted by the same origin policy and so doesn't need CORS. – Quentin Feb 10 '16 at 13:23
  • @fsulser — http://stackoverflow.com/a/35311165/19068 — that answers your question. It's more-or-less a duplicate (but a lack of upvotes / accepted answers means I can't vote to close this as a duplicate). – Quentin Feb 10 '16 at 13:25

1 Answers1

0

I added a CORS filter on the server-side as shown below, but I still get this error:

XMLHttpRequest cannot load "URL". 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:8080' is therefore not allowed access. The response had HTTP status code 401.

Is something wrong with my CORS definition?

@WebFilter(urlPatterns = "/*", filterName = "simpleCORSFilter")
public class SimpleCORSFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(SimpleCORSFilter.class);

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    response.setHeader("Access-Control-Max-Age", "10"); // in seconds
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    logger.info("doFilter() called: " + request.getMethod());
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {
}

public void destroy() {
}

}
fsulser
  • 853
  • 2
  • 10
  • 34