0

我需要调用两个不同的 API:第一个用于登录,第二个用于提取数据。

第一次登录存储必须在第二次请求中使用的 Cookie。

在PHP中我已经实现了这个过程如下

$login_url = 'EXTERNALWEBSITE/login';

//These are the post data username and password
$post_data = 'email=EMAIL&pwd=PWD';

//Create a curl object
$ch = curl_init();

//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];   
curl_setopt($ch, CURLOPT_USERAGENT, $agent);

//Set the URL
curl_setopt($ch, CURLOPT_URL, $login_url );

//This is a POST query
curl_setopt($ch, CURLOPT_POST, 1 );

//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

//Execute the action to login
$postResult = curl_exec($ch);

$url = 'EXTERNALWEBSITE/secondapi'; 

curl_setopt_array(
$ch, array(
CURLOPT_URL => $url ,
CURLOPT_RETURNTRANSFER => true
));

$output = curl_exec($ch);
    
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch).'<br/>';        
    $output = null;
} 

curl_close ($ch);

return $output;

NodeJS 中使用 GOT 库或类似方法的方式是什么?我尝试了很多建议但没有成功。这是我不工作的解决方案

login().then(res => {

        getData(res.headers['set-cookie'][0]);
        
    })
    .catch(err => {
        console.log('Error: ', err.message);
    }); 

  const login = () => {

const options = {
    prefixUrl: constants.BASEURL,
    json: {
        email: constants.USER,
        pwd: constants.PASSWORD
    }
};

return got.post(constants.LOGINURL, options);

}   

const getData= async (cookie) => {


const options = {
    prefixUrl: constants.BASEURL,
    headers: {
        Cookie: cookie
    }
};


const res = await got.post(constants.DATAURL, options);


}

谢谢!

4

1 回答 1

1

我已经使用库 node-libcurl 解决了。这里的代码

const cookie = 'cookie.txt';

var { statusCode, data, headers } = await curly.post(constants.BASEURL+constants.LOGINURL, {
    postFields: querystring.stringify({
        pwd: constants.PASSWORD,
        email: constants.AUSER
    }),
    followLocation: true,
    cookieFile: cookie,
    cookieJar: cookie,
    sslVerifyPeer: false,
    post: true
});

var { statusCode, data, headers } = await curly.get(constants.BASEURL+constants.DATAIURL, {
    followLocation: true,
    cookieFile: cookie,
    cookieJar: cookie,
    sslVerifyPeer: false
});


return data;

在顶部声明 cookie const,cookieJar 在两个调用之间共享,因此您可以模拟由 cookie 管理的会话。

谢谢!

于 2021-09-03T07:51:30.950 回答