自动登录网站

时间:2017-12-06 20:51:08

标签: javascript node.js http postman axios

我正在NodeJS上开发代码解决方案以自动登录此网站http://panel2.gpscontrol.cl我在身份验证的时刻遇到了问题,但我在Postman App上做同样的事情并且效果很好,但我的代码不是& #39;吨

let axios = require('axios');
let cheerio = require('cheerio');
let queryString = require('querystring');

let login = async function () {
try {
    let response = await axios.get('http://panel2.gpscontrol.cl');
    let $ = cheerio.load(response.data);
    let cookie = response.headers['set-cookie'];
    cookie[0] = cookie[0].split(';')[0];
    cookie[1] = cookie[1].split(';')[0];
    console.log(cookie);
    let token = $('input[name="_token"]').val();
    let subdominio = $('input[name="subdominio"]').val();
    let body = {
        _token: token,
        subdominio: subdominio,
        login: '**********',
        password: '***************'
    }
    let options = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
            Accept: '*/*',
            Connection: 'keep-alive',
            'accept-encoding': 'gzip, deflate',
            cookie: cookie
        }
    }
    console.log('--------------------------------------');
    console.log(queryString.stringify(body));
    console.log('--------------------------------------');
    let loggedPageData = await axios.post('http://panel2.gpscontrol.cl/auth/login',
        queryString.stringify(body), options);
    let loggedCookies = loggedPageData.headers['set-cookie'];
    options = {
        headers: {
            cookie: loggedCookies
        }
    }        
    console.log(loggedPageData);
} catch (error) {
    console.error(error);
}
}

login();

我希望结果是Postman请求的结果是http://panel2.gpscontrol.cl/home的html代码。

实际结果是登录html代码http://panel2.gpscontrol.cl/http://panel2.gpscontrol.cl/auth/login

0 个答案:

没有答案