什么是 unirest?
unirest 是一个流行的 Node.js 包,提供了基于 Promise 的 HTTP 请求,支持多种请求方法和各种格式的响应。
使用 unirest 可以更加方便地进行网络请求,不需要自己手写很多请求头,并且可以轻松处理 HTTP 和 HTTPS。
安装和使用
安装 unirest
npm install unirest
导入 unirest
const unirest = require('unirest');
发送请求
以 GET 请求为例:
unirest.get('http://httpbin.org/get') .query({ name: 'John', age: 25 }) .end(function (response) { console.log(response.body); });
代码解释:
get
方法用于发送 GET 请求。query
方法用于在 URL 查询字符串中添加参数。end
方法是一个回调函数,用于处理响应。
响应体中的
response.body
就是响应的内容,可以进行其他操作。
简单示例
假设需要发送一个 POST 请求,发送 JSON 数据到服务器上。
请求的 URL 为 http://localhost:3000/submitData
,请求体中包含一个字段 name
和一个字段 age
。
使用 unirest 可以这样实现:
unirest.post('http://localhost:3000/submitData') .headers({ 'Content-Type': 'application/json' }) .send({ 'name': 'John', 'age': 25 }) .end(function (response) { console.log(response.body); });
代码解释:
post
方法用于发送 POST 请求。headers
方法用于设置请求头。send
方法用于设置请求体。- 响应同上。
深入理解
发送完整的请求
unirest 支持发送完整的请求体。这个适用于以下场景:请求体很大,文件上传等。
let req = unirest.post('http://localhost:3000/uploadFile'); req.headers({ 'Content-Type': 'text/plain' }); let stream = fs.createReadStream('path/to/file'); stream.pipe(req); req.end(function (response) { console.log(response.body); });
以上代码向 localhost:3000/uploadFile
发送了一个 text/plain
类型的文件,使用了 Node.js 的可读流。
发送 x-www-form-urlencoded 表单数据
如果需要发送表单数据,可以使用 form
方法。
unirest.post('http://localhost:3000/post') .headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) .form({ 'username': 'John', 'password': 'password' }) .end(function (response) { console.log(response.body); });
如果表单数据需要以 JSON 形式发送,可以使用 json
方法。
unirest.post('http://localhost:3000/post') .headers({ 'Content-Type': 'application/json' }) .json({ 'username': 'John', 'password': 'password' }) .end(function (response) { console.log(response.body); });
发送文件
使用 unirest 发送文件可以这样实现:
unirest.post('http://localhost:3000/uploadFile') .headers({ 'Content-Type': 'multipart/form-data' }) .field('name', 'John') .field('age', 25) .attach('file', 'path/to/file') .end(function (response) { console.log(response.body); });
以上代码向 /uploadFile
发送了一个文件,文件名为 file
。在请求头中设置了 multipart/form-data
,并且在请求体中设置了两个参数 name
和 age
。
错误处理
unirest 可以非常方便地处理 HTTP 错误。可以在 end 回调函数中判断响应的状态码是否是 200,如果不是,根据错误码进行相应的处理。
-- -------------------- ---- ------- ------------------------------------------ ------------- ---------- - -- -------------------- --- ---- - -------------------- - --------------------- --------------------- - --------------------- ------- - --------------------------- ---展开代码
总结
本文介绍了 npm 包 unirest 的使用方法。通过本文的介绍,读者可以轻松地进行 HTTP 和 HTTPS 请求,并且进行深入的参数控制和错误处理。本文同时提供了多个示例代码,使读者能够更加深入理解 unirest 的使用方法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/unirest