跳到主要内容

Axios GET 请求

TypeScript 支持

为了在 CommonJS 中使用 require() 导入时获得 TypeScript 类型推断,请使用以下方法:

const axios = require("axios").default

// axios.<method> 能够提供自动补全和参数类型推断功能

使用 Axios 发起一个 GET 请求

方法一:基本 GET 请求

const axios = require("axios")

// 向给定 ID 的用户发起请求
axios
.get("/user?ID=12345")
.then(function (response) {
// 处理成功情况
console.log(response)
})
.catch(function (error) {
// 处理错误情况
console.log(error)
})
.finally(function () {
// 总是会执行
})

方法二:使用 params 对象

const axios = require("axios")

axios
.get("/user", {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
.finally(function () {
// 总是会执行
})

方法三:使用 async/await

const axios = require("axios")

async function getUser() {
try {
const response = await axios.get("/user?ID=12345")
console.log(response)
} catch (error) {
console.error(error)
}
}
提示

注意: 由于 async/await 是 ECMAScript 2017 中的一部分,而且在 IE 和一些旧的浏览器中不支持,因此请谨慎使用。