在Node中使用Axios的HTTP请求的方法

3,478 阅读2分钟

Axios是一个非常方便的JavaScript库,可以在Node.js中执行HTTP请求

简介

Axios是一个非常流行的JavaScript库,你可以用来执行HTTP请求,它可以在浏览器和Node.js平台上工作。

它支持所有的现代浏览器,包括对IE8和更高版本的支持。

它是基于承诺的,这让我们可以非常容易地编写异步/等待代码来执行XHR请求。

与本地的Fetch API相比,使用Axios有很多优势。

  • 支持旧的浏览器(Fetch需要一个polyfill)。
  • 有一种方法可以中止一个请求
  • 有办法设置响应超时
  • 有内置的CSRF保护
  • 支持上传进度
  • 执行自动JSON数据转换
  • 在Node.js中工作

一个视频教程

请看这个视频,我创建了一个提供POST端点的Express服务器,并向其发出Axios请求,以发布数据。

安装

Axios可以用npm安装。

yarn:

或使用unpkg.com将其包含在你的页面中。

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios的API

你可以从axios 对象启动一个HTTP请求。

我使用foobar 作为随机名称。输入任何种类的名字来代替它们。

axios({
  url: 'https://dog.ceo/api/breeds/list/all',
  method: 'get',
  data: {
    foo: 'bar'
  }
})

但为了方便,你一般会使用

  • axios.get()
  • axios.post()

(就像在jQuery中你会使用$.get()$.post() 而不是$.ajax())

Axios为所有的HTTP动词提供了方法,这些动词不太流行,但仍在使用。

  • axios.delete()
  • axios.put()
  • axios.patch()
  • axios.options()

和一个方法来获取一个请求的HTTP头信息,放弃正文。

  • axios.head()

GET请求

使用Axios的一个方便方法是使用现代(ES2017)的async/await语法。

这个Node.js例子查询Dog API,检索所有狗的品种列表,使用axios.get() ,并对它们进行统计。

const axios = require('axios')

const getBreeds = async () => {
  try {
    return await axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = await getBreeds()

  if (breeds.data.message) {
    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
  }
}

countBreeds()

如果你不想使用async/await,你可以使用Promises语法。

const axios = require('axios')

const getBreeds = () => {
  try {
    return axios.get('https://dog.ceo/api/breeds/list/all')
  } catch (error) {
    console.error(error)
  }
}

const countBreeds = async () => {
  const breeds = getBreeds()
    .then(response => {
      if (response.data.message) {
        console.log(
          `Got ${Object.entries(response.data.message).length} breeds`
        )
      }
    })
    .catch(error => {
      console.log(error)
    })
}

countBreeds()

在GET请求中添加参数

一个GET响应可以在URL中包含参数,像这样:https://site.com/?foo=bar

使用Axios,你可以通过使用该URL来执行。

axios.get('https://site.com/?foo=bar')

或者你可以在选项中使用params 属性。

axios.get('https://site.com/', {
  params: {
    foo: 'bar'
  }
})

POST请求

执行POST请求就像做GET请求一样,但你用axios.get ,而不是axios.post

axios.post('https://site.com/')

一个包含POST参数的对象是第二个参数。

axios.post('https://site.com/', {
  foo: 'bar'
})