将curl-command转换为ajax请求

时间:2016-02-10 13:01:55

标签: php jquery ajax authentication curl

与此问题相关Convert curl-command to php curl我正在尝试将curl语句转换为ajax请求。

我的请求是使用以下curl-command:

curl --user XXXX:YYYY "URL"

但是试图在jquery ajax中使用它它不起作用,我的代码看起来像:

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

我还试图设置一个beforeSend值,如下所示:

$.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);
});

在这两种情况下,我都会遇到同样的错误:

  

XMLHttpRequest无法加载   “URL”。回应   预检具有无效的HTTP状态代码401

有谁知道如何解决这个问题?

更新

标题如下所示:

常规

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

响应标题

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

请求标题

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

1 个答案:

答案 0 :(得分:0)

我在服务器端添加了一个CORS过滤器,如下所示,但我仍然收到此错误:

  

XMLHttpRequest无法加载“URL”。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:8080”访问。响应的HTTP状态代码为401。

我的CORS定义有问题吗?

<Button Content="YourText" Backround="..." Foreground="..." Style="..." />