首页 > 解决方案 > 如何使子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 问题,我该如何实现这部分?

标签: node.jscurlhttpsrequesthttprequest

解决方案


只需在第一个回调中执行第二个请求。您使用 有什么特别的原因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);
});

希望有帮助!


推荐阅读