Cookie 在 Spotify (Javascript) 中调用 ajax 后未保存

Cookie not being saved after an ajax call in Spotify (Javascript)?

本文关键字:ajax 调用 保存 Spotify Javascript Cookie      更新时间:2023-09-26

我正在开发一个Spotify应用程序,我也在尝试使用JQuery的$.ajax函数登录Reddit。登录有效,我可以在开发工具中看到响应cookie,但是当我尝试访问Reddit的API的任何部分时,该部分要求在调用时发送登录cookie,它失败了,看起来cookie永远不会被发送。此外,查看开发工具的"Cookie"部分会显示该网站(应用程序)没有 Cookie。

这是登录调用:

$.ajax({
    type: 'POST',
    url: 'http://www.reddit.com/api/login',
    data: {
        'user': $user,
        'passwd': $password
    },
    success: function() {
        alert("logged in!");
    }
});

这是投票调用(用户哈希从我可以在开发工具中看到的cookie复制):

$.ajax({
    type: 'POST',
    url: 'http://www.reddit.com/api/vote',
    data: {
        'id': $id,
        'dir': 1,
        'uh': $userhash
    },
    success: function(data) {
        console.log(data);
    }
});

使用 jQuery 1.5.1 中添加的 xhrFields 属性可能会有所帮助:

登录调用:

$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/login',
data: {
    'user': $user,
    'passwd': $password
},
xhrFields: {
   withCredentials: true
},
success: function() {
    alert("logged in!");
}
});

投票电话:

$.ajax({
type: 'POST',
url: 'http://www.reddit.com/api/vote',
data: {
    'id': $id,
    'dir': 1,
    'uh': $userhash
},
xhrFields: {
   withCredentials: true
},
success: function(data) {
    console.log(data);
}
});

这将告诉它将 XMLHTTPRequest 对象的 withCredentials 属性设置为 true,这是使用跨域 AJAX 调用时传递 cookie 所必需的。