jQuery ajax请求有多个部分自定义标头?

时间:2014-02-21 03:11:26

标签: javascript jquery ajax

我有一个基本的ajax请求,我正在尝试将自定义标头附加到:

_auth=1,[my_apikey],

我可以使用具有相同请求的邮递员,并且它正确返回json响应。该请求因401: Unauthorized而失败,因此我认为我的标题未正确附加。

如何正确地将多部分自定义标头添加到ajax请求?

完整的ajax请求:

$(function(){
   $.ajax({
        url: "https://r-test.ordr.in/dl/ASAP/10012/New%20York/568%20Broadway?_auth=1,3EJjhE07gEYumzByF9hM0c3q7xjf1ZiZOOwngk1MCoU",
        dataType: 'jsonp',
        headers: {"X-NAAMA-CLIENT-AUTHENTICATION": "id='[my_apikey]', version='1'"},
        success: function(response){alert(response)},
        error: function(jqXHR, status, error){alert(error)}
    });
});

来自开发工具的请求标头:

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:SS_MID=14f520bc-d926-4ff3-a5cc-f5c682b758f5hrl1wmzt; ss_cid=cc24fc87-e81d-4ed6-a313-24e04cfbfd72; __utma=86046534.1735612382.1392236906.1392746695.1392826972.3; __utmc=86046534; __utmz=86046534.1392236906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __auc=2a449d7614427c94751a82169e5
Host:r-test.ordr.in
Pragma:no-cache
Referer:http://localhost:8000/curate/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36

邮递员回复示例:

[
    {
        "id": 32096,
        "na": "Nuchas",
        "cs_phone": "212-363-0120",
        "rds_info": {
            "id": 186,
            "name": "delivery.com",
            "logo": ""
        },
        "services": {
            "deliver": {
                "time": 2865,
                "mino": 144,
                "can": 0
            }
        },
        "allow_tip": 1,
        "allow_asap": 1,
        "cu": [
            "Empanadas"
        ],
        "addr": "1514 Broadway, New York, NY",
        "full_addr": {
            "addr": "1514 Broadway",
            "addr2": "",
            "city": "New York",
            "state": "NY",
            "postal_code": "10036-4002"
        },
        "city": "New York",
        "latitude": 40.757627,
        "longitude": -73.985512,
        "del": 2865,
        "mino": 144,
        "is_delivering": 0
    },
]

1 个答案:

答案 0 :(得分:1)

我认为您不能对所述资源进行ajax调用,因为jsonp不允许自定义标头,并且所述资源不支持CORS ...

因此,我能看到的唯一可行的解​​决方案是让您的Web服务器充当代理,在那里您向Web服务器发送了一个ajax请求,该请求调用远程资源来获取值,一旦获取了服务器可以将结果返回给客户端。

此外,由于远程资源是带有API密钥的安全资源,因此将密钥发送到客户端是不明智的,因为任何人都可以看到并使用它。