首页 > 解决方案 > 未在 API 调用上的跨子域请求上发送 Cookie

问题描述

我有一个页面存储在https://page.domain.com上。在这里,我使用 javascript(主要是 Bootstrap)从https://api.domain.com获取数据。第一次调用,当页面加载时,是一种“某种”身份验证调用,它在标题中返回一个 cookie:

set-cookie: oauth=emd4YWgybTJobmJnZjVrbXl2ZjdlZThiOzkzczg1YWt2YzNyZW42cjk3M2U4dXlweA==; domain=.domain.com; path=/; expires=Fri, 16 Apr 2021 11:58:07 GMT;

我可以在开发人员工具 (Chrome) 中看到 cookie 存储正确。

但是,当我进行下一个 api 调用(例如,填充下拉列表 - 引导自动完成)时,cookie 不在请求中。当我在 localhost(我猜是相同的“域”)中构建它时,这工作正常,但是现在,在不同的域上运行 html 和 api,似乎没有共享 cookie。我认为这可能是因为两个不同的域,但是根据文档,当将 cookie 设置为主域时,所有子域都应该能够共享它。(另外,我包括“withCredentials”标志)

这是初始调用的代码(并设置后续调用):

    $.ajax({url: 'https://api.domain.com/get-cookie',
        xhrFields: {
          withCredentials: true
        }
      })
    .done(function (response) {

  $('.selectpicker').selectpicker().ajaxSelectPicker({
    ajax: {
      // data source
      url: 'https://api.domain.com/data.json',
      // ajax type
      type: 'GET',
      // data type
      dataType: 'json',
      // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
      // automatically replace it with the value of the search query.
      data: {
        q: '{{{q}}}'
      }
    },
    // function to preprocess JSON data
    preprocessData: function (data) {
      var i, l = data.length, array = [];
      if (l) {
        for (i = 0; i < l; i++) {
          array.push($.extend(true, data[i], {
            text : data[i].name,
            value: data[i].code,
            data : {
              subtext: data[i].code
            }
          }));
          localStorage.setItem(data[i].code, data[i].name);
        }
      }
      // You must always return a valid array when processing data. The
      // data argument passed is a clone and cannot be modified directly.
      return array;
    }     
  });
    }
);

我正在使用 AWS API Gateway 和 Lambda 函数,但这不应该是相关的......


从 selectPicker 获取 url(例如:https://api.domain.com/data.json)并将其直接放在浏览器中时,我看到正在发送 cookie。这似乎表明问题可能出在未正确发送标头的 Bootstrap Select 组件中。我不确定我是否可以使其按预期工作,或者我必须找到其他替代方案。

标签: javascriptjqueryajaxcookiesbootstrap-select

解决方案


解决方案是在选择器请求中也包含 withCredentials:

$('.selectpicker').selectpicker().ajaxSelectPicker({
    ajax: {
      // data source
      url: 'https://api.domain.com/data.json',
      // ajax type
      type: 'GET',
      // data type
      dataType: 'json',
      // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
      // automatically replace it with the value of the search query.
      data: {
        q: '{{{q}}}'
      },
      xhrFields: {
        withCredentials: true
      }
    },
    // function to preprocess JSON data
  preprocessData: function (data) {
        // ...
  }     
 });
 }
);

感谢@CBroe 在评论中的想法。


推荐阅读