【发布时间】:2021-09-02 14:41:42
【问题描述】:
我需要调用两个不同的 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);
}
谢谢!
【问题讨论】:
-
"Cookies" 只是 http 标头,将它们存储在您想要的任何位置,并在您执行 http 请求时设置它们。无需外部模块即可完成。
-
我已经尝试将 res.headers['set-cookie'][0] 传递给 Cookie 标头。但它不起作用。
-
添加你的 node.js 代码。
标签: javascript node.js web-scraping cookiejar node.js-got