在学习node的过程中一开始都是在处理外部的请求,但是如果碰到第三方接口的请求怎么办呢?
这里有两种方法。一种是node原生request请求一种是引用koa2-request中间件的方法。
node原生request请求
这里我们分为get请求和post请求(原生node的request是需要手动引入的)
get请求有以下两种,第一种直接将要的参数全部写到url里面;第二种将要传的参数写到qs字段中。这两种方法的效果是一样的。传入的第二个参数为回调函数,回调函数中的第二个参数才是返回的数据,第一个参数是请求错误的信息。
const koaReq = require('request') //node封装的请求中间件 // node封装的请求中间件http请求 var resData = { token: '6caad2f73e5977948de7937af924cca7', start: 0, count: 10 } module.exports = function () { return async function (ctx,next) { // node封装的请求中间件GET请求 // await koaReq('http://api.douban.com/v2/movie/top250?start=25&count=2', function (error, response, body) { // if (!error && response.statusCode == 200) { // console.log(JSON.parse(body)) // } // }) await koaReq({ method: 'get', uri: 'http://api.douban.com/v2/movie/top250', qs: { start: 25, count: 2 }, json: true//设置返回的数据为json },function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) } }) //node封装的请求中间件POST请求(request) await koaReq({ url: 'http://rental.heyhat.cn/agentOrder/user_info_list', method: 'post', form: resData, json: true//设置返回的数据为json }, function (err,res,body) { if (!err && res.statusCode == 200) { console.log(body) } }) await next() } }
koa2-request中间件请求
res是get请求,res1是post请求
const koaRequest = require('koa2-request') //koa封装的请求第三方接口的方法 var resData = { token: '6caad2f73e5977948de7937af924cca7', start: 0, count: 10 } module.exports = function () { return async function (ctx,next) { //koa封装的请求第三方接口的方法(koa2-request) let res = await koaRequest({ url: 'http://api.douban.com/v2/movie/top250', method: 'get', qs: { start: 25, count: 2 } }); // let res = await koaRequest('http://api.douban.com/v2/movie/subject/26942674'); let res1 = await koaRequest({ url: 'localhost:3030/test', method: 'post', form: resData }) console.log(JSON.parse(res.body),JSON.parse(res1.body)) await next() } }
koa2-request是在原生request的基础上封装的使用方式是一样的,两种发送请求的方式是类似的随便选一种就行了