xhr请求:如何获取x-csrftoken?

时间:2018-09-15 09:44:50

标签: xmlhttprequest token csrf

嗨,我尝试发出XHR请求,但我需要令牌。当我尝试使用此代码来获取它时:

http.setRequestHeader('x-csrftoken', 
window._sharedData.config.csrf_token);

它给我一个错误:

  

window._sharedData未定义

你有什么主意吗?

这是我的完整代码:

function check_insta(username, password){
    var params = "username="+username+"&password="+password;

    new Promise(function (resolve, reject) {
        var http = new XMLHttpRequest();
        console.log(window._sharedData);
        http.open("POST", "https://www.instagram.com/accounts/login/ajax/", true);
        http.setRequestHeader('x-csrftoken', window._sharedData.config.csrf_token);
        http.setRequestHeader('x-instagram-ajax', '1');
        http.setRequestHeader('x-requested-with', 'XMLHttpRequest');
        http.setRequestHeader("pragma", "no-cache");
        http.setRequestHeader("cache-control", "no-cache");
        http.setRequestHeader("accept-language", "en-US,en;q=0.8,it;q=0.6");
        http.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status !== 200) {
                console.log('error'+ http.status);
                reject('error: ' + http.status);
            };
            if (http.readyState == 4 && http.status == 200) {
                var json = JSON.parse(http.response);
                if (!json.authenticated) {
                    console.log('wrong pwd');
                    reject('bad password');
                } else if (json.authenticated && json.user && json.status === 'ok') {
                    console.log('success cookie');
                    resolve('success:', document.cookie);
                };
            };
        };
        http.send(params);
    }).catch(function (error) {
        console.log(error);
    });
}

0 个答案:

没有答案