牧羊人nacy
2022-07-01 15:52:39
我有一個頁面存儲在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 組件中。我不確定我是否可以使其按預期工作,或者我必須找到其他替代方案。
1 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
解決方案是在選擇器請求中也包含 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) {
// ...
}
});
}
);
添加回答
舉報
0/150
提交
取消