Node.js中axios的使用 转

转自:https://www.cnblogs.com/itech/p/13253319.html

http相关modules

  • HTTP – the Standard Library
  • Request
  • Axios
  • SuperAgent
  • 推荐使用axios 或者super agent

使用axios和superagent的get

const axios = require('axios');

axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

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);
});

使用axios的post

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(Status: <span class="hljs-subst">${res.status}</span>);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

 

转自:https://www.cnblogs.com/JasmineLily/p/11157701.html

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)
   })
} 
点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注