node.js - 如何使子HTTP请求nodejs
问题描述
我有 2 部分 php cURL 代码可以正常工作。我必须在 NODE JS 中实现。我有 2 个请求。首先我必须登录,然后执行操作。
// login part
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, "https://my.example.com/mypage/?regid=" . username
. "&password=" . $password . "");
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT ,30);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 60);
curl_setopt($this->curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($this->curl);
// action part
curl_setopt($this->curl, CURLOPT_URL, "https://my.example.com/mypage/action/");
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $myFields);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$content = curl_exec($this->curl);
我能够实现第一部分,我在 console.log() 中看到了答案(正文)。
const curl = new (require( 'curl-request' ))();
curl.setHeaders([
]).setBody({
'regid': username,
'password': regpass
})
.post(registry)
.then((answer) => {
console.log('answer', answer.body);
})
.catch((e) => {
console.log(e);
});
但我无法实现第二个请求。我试着做这个例子: how to make sub HTTP request using nodejs
据我了解 cookie 问题,我该如何实现这部分?
解决方案
只需在第一个回调中执行第二个请求。您使用 有什么特别的原因curl
吗?使用直接 HTTP 请求库(如axios
. 这是我所知道的,所以curl
如果你真的需要的话,你可以把它翻译成。
const axios = require('axios');
axios({
method: 'post',
url: 'https://my.example.com/mypage',
headers: {
'X-Example-Header': 'you can send your headers here'
}
params: {
regid: 'you can put your query params here and they will be added to the URL automatically'
}
data: {
// this is the request body data
regid: username,
password: regpass
}
}).then(res1 => {
// res1.data holds the response body
// res1.headers holds the response headers
// if the header you want contains dashes, you have to access it like this:
// res1.headers['X-Example-Header']
axios({
method: 'post',
url: 'https://my.example.com/mypage/action'
}).then(res2 => {
// res2.data === response of second request
}, err => {
console.log(err.response.data);
});
}, err => {
// this function triggers if the response is a 4xx or 5xx
// err.response.data is the response body for the error
console.log(err.response.data);
});
希望有帮助!
推荐阅读
- ansible - 如何从 ansible_facts 获取“cifs”挂载的“用户名”?
- vim - 如何使 vim 的 vimgrep 命令保持缩进?
- css - Vuetify 的网格与引导网格兼容吗?
- python-3.x - NameError:名称“锁”未定义
- machine-learning - 删除缺失值百分比较高的列后的不同 test_set 和 train_set 维度
- javascript - 如何从多个对象数组中过滤数据
- go - 如何为指向不同结构的指针实现相同的功能?
- class - Apex 类扩展:使用标准控制器更新相关字段
- html - 请勿使用以下字符:< > ( ) [ ] ; : , \ 在电子邮件验证模式中
- arrays - Kotlin UByteArray 和 System.arraycopy