当前位置: 首页 > 工具软件 > Planetary.js > 使用案例 >

使用node.js发起get和post请求的五种方式

羊舌高峰
2023-12-01

项目中需要构造请求参数发起get和post请求,遂记录

Request

Request 是一个简化的http客户端,它和Python的request库很像。这个库比默认的 http 模块更好用,多年来被开源社区作为开发首选。

与 http 模块不同的是,你必须使用npm来安装它。

在终端下进入到你想要代码被下载的目录中,运行以下命令:

npm install request@2.81.0

代码实现如下

const request = require('request');
  
request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
 if (err) { return console.log(err); }
 console.log(body.url);
 console.log(body.explanation);
});

Axios

Axios 是一个基于promise的HTTP客户端,可以用于浏览器和Node.js。在处理需要更复杂的事件链的代码时,使用Promises具有很大的优势。 编写异步代码可能会令人困惑,而Promises是这个问题的几种解决方案之一。 它们甚至被用在其它语言中,比如Swift。

使用npm安装Axios,在终端中输入以下命令:

npm install axios@0.16.2

代码实现如下

const axios = require('axios');  
axios.get('http://xx.xx.xxx.xxx:xxxx/product/test?name=zhangxi&code=1234')
 .then(function (response) {
    console.log(response.data);
  })
 .catch(error => {
  console.log(error);
 });

默认情况下,Axios可以解析JSON响应,非常方便。你也可以看到错误处理是由 .catch() 完成的,现在我们都在使用 promises。

你甚至可以通过 axios.all 发起多个并发请求,比如说你想一次性得到两天的天文图片可以这样做

 var axios = require('axios');
  
axios.all([
 axios.get('http://xx.xx.xxx.xxx:xxxx/product/test?name=zhangxi&code=1234'),
 axios.get('http://xx.xx.xxx.xxx:xxxx/product/test?name=xiaoming&code=3456')
]).then(axios.spread((response1, response2) => {
 console.log(response1.data);
 console.log(response2.data);
})).catch(error => {
 console.log(error);
});

SuperAgent

与Axios类似, SuperAgent 是另一个流行的库,主要用于浏览器中的Ajax请求,但也适用于Node.js。使用以下命令安装SuperAgent :

npm install superagent@3.5.2

SuperAgent最酷的地方是能进行链式调用,你可以把其它函数链到像 query() 这样的请求上,并且添加参数。在前面的例子中我们都是手动添加它们。请注意 SuperAgent 是怎样提供这种功能的:

const superagent = require('superagent');
  
superagent.get('https://api.nasa.gov/planetary/apod')
.query({ api_key: 'DEMO_KEY', date: '2017-08-02' })
.end((err, res) => {
 if (err) { return console.log(err); }
 console.log(res.body.url);
 console.log(res.body.explanation);
});

Got

如果你想用一个更轻量级的库,Got是另外一个选择。它也可用于Twilio Functions

再来一遍,实用npm安装Got:

npm install got@7.1.0
const got = require('got');
  
got('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }).then(response => {
 console.log(response.body.url);
 console.log(response.body.explanation);
}).catch(error => {
 console.log(error.response.body);

以上并不是全部的解决方案,不过记录到这里,了解了在Node.js中一些流行的HTTP库中的基本功能是怎样工作的。还有一些库,例如node-fetch将浏览器的获取(fetch)功能移植到后端。在其他语言中也有各种类似的库解决这个问题,比如 Python 和 Ruby 。

 类似资料: