NodeJS中axios的使用案例
最近工作遇到需求,要测验一下第三方公司给我们提供的API是否可行,其实方法有至少两种,一是利用postman,设置基本信息,然后点击按钮测验;一是nodeJS,代码访问API。当然作为coder,本人选择了后者。下面上一些基本的格式,以防下次还需要用到,就会省很多查询的麻烦。
Methods: POST
- Protocol : HTTP
- Data Format : x-www-form-urlencoded
- Response Data : JSON
const axios = require("axios"); const Qs = require("qs"); //qs是一个url参数转化(parse/stringify)的js库 async function testPOST() { let response = await axios({ method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, url: url, data: Qs.stringify(param) }) console.log(response) }
Methods: GET
- Protocol : HTTP
- Data Format : x-www-form-urlencoded
- Response Data : JSON
const axios = require("axios"); const path = require("path"); const fs = require("fs"); const filePath = "E:\\testAPI" //希望把文件下载到哪里 async function testGET(){ if (!fs.existsSync(filePath)) { fs.mkdirSync(filepath) } /* name是生成的文件的文件名,自定义,比如,我希望产生的文件名为test.pdf,那么name='test.pdf' */ const mypath = path.resolve(filePath, name) const writer = fs.createWriteStream(mypath) let response = await axios({ url: resource, //需要访问的资源链接 method: "GET", responseType: "stream", params: param //需要传的参数 }) response.data.pipe(writer) return new Promise((resolve, reject) => { writer.on("finish", resolve) writer.on("error", reject) }) }
细水长流才是真。Nothing is impossible!