【问题标题】:Cross domain jquery ajax api call with custom headers is not hitting the server带有自定义标头的跨域 jquery ajax api 调用未命中服务器
【发布时间】:2014-09-16 00:32:43
【问题描述】:

我想使用 jquery ajax(带有自定义标头)从客户端调用 Web 服务。我几乎做到了。我已经将 Access-Control-Allow-Origin 设置为 force.com 和 salesforce.com,因为我是从 salesforce 调用网络服务的。

当我尝试在没有自定义标头的情况下调用该 API 时,它会获得响应,而当我使用标头调用时,它不会获得响应。

带有自定义标题

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('orgid', '00D90000000oxxxx');
        xhr.setRequestHeader('userid', '00590000001Dxxxxxx');
    },
    success: function(response) {
        alert('success' + JSON.stringify(response));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

也试过

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    headers: {
        "orgid": "00D90000000oxxxx",
        "userid": "00590000001Dxxxxxx",
    },

    success: function(data) {
        alert(JSON.stringify(data));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

但在上述两种情况下,它都没有访问服务器并收到错误消息

当我不使用任何标头时,它会访问服务器

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    success: function(response) {
        alert('success' + JSON.stringify(response));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

它得到了成功响应

在响应标头中显示

Access-Control-Allow-Headers: Content-Type

只有 content-type 存在,是这个问题吗? 我们是否需要在此处添加自定义标头?

当我使用 firefox firebug 分析网络时,它显示如下

  1. POST 寄存器(未传递任何标头)
  2. 选项注册(带有自定义标题)

我不知道为什么会这样

谁能帮忙。

在此先感谢..:)

【问题讨论】:

    标签: javascript jquery ajax api cross-domain


    【解决方案1】:

    尝试在您正在调用的服务的“Access-Control-Allow-Headers”列表中添加您的自定义标头(orgId 和 userId)。

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 2012-01-30
      • 2016-02-21
      • 2015-05-26
      • 2012-10-21
      相关资源
      最近更新 更多