我需要调用两个不同的 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);
}
谢谢!