当前位置:   article > 正文

axios的用法_axios 使用

axios 使用

1、什么是axios

  • Axios 是专注于网络数据请求的库。
  • 相比于原生的 XMLHttpRequest 对象,axios 简单易用
  • 相比于 jQuery,axios 更加轻量化,只专注于网络数据请求。

功能特点:

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 等等

2、axios请求方式

支持多种请求方式:

  1. axios(config)
  2. axios.request(config)
  3. axios.get(url[, config])
  4. axios.delete(url[, config])
  5. axios.head(url[, config])
  6. axios.post(url[, data[, config]])
  7. axios.put(url[, data[, config]])
  8. axios.patch(url[, data[, config]])

有时候, 我们可能需求同时发送两个请求

  • 使用 axios.all, 可以放入多个请求的数组.
  • axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2 

3、常见的配置选项

参数

说明

请求地址

url: '/user',

请求类型

method: 'get',

请根路径

baseURL: 'http://www.mt.com/api',

请求前的数据处理

transformRequest:[function(data){}],

自定义的请求头

headers:{'x-Requested-With':'XMLHttpRequest'},

URL查询对象

params:{ id: 12 },

查询对象序列化函数

paramsSerializer: function(params){ },

request body

data: { key: 'aa'},

超时设置

timeout: 1000,

请求后的数据处理

transformResponse: [function(data){}],

4、示例代码

4.1、常见请求演练 

  1. // 1.发送request请求
  2. axios.request({
  3. url: "http://123.207.32.32:8000/home/multidata",
  4. method: "get"
  5. }).then(res => {
  6. console.log("res:", res.data)
  7. })
  8. // 2.发送get请求
  9. axios.get(`http://123.207.32.32:9001/lyric?id=500665346`).then(res => {
  10. console.log("res:", res.data.lrc)
  11. })
  12. axios.get("http://123.207.32.32:9001/lyric", {
  13. params: {
  14. id: 500665346
  15. }
  16. }).then(res => {
  17. console.log("res:", res.data.lrc)
  18. })
  19. // 3.发送post请求
  20. axios.post("http://123.207.32.32:1888/02_param/postjson", {
  21. name: "coderwhy",
  22. password: 123456
  23. }).then(res => {
  24. console.log("res", res.data)
  25. })
  26. axios.post("http://123.207.32.32:1888/02_param/postjson", {
  27. data: {
  28. name: "coderwhy",
  29. password: 123456
  30. }
  31. }).then(res => {
  32. console.log("res", res.data)
  33. })

4.2、额外补充

  1. // 1.baseURL
  2. const baseURL = "http://123.207.32.32:8000"
  3. // 给axios实例配置公共的基础配置
  4. axios.defaults.baseURL = baseURL
  5. axios.defaults.timeout = 10000
  6. axios.defaults.headers = {}
  7. // 1.1.get: /home/multidata
  8. axios.get("/home/multidata").then(res => {
  9. console.log("res:", res.data)
  10. })
  11. // 1.2.get: /home/data
  12. // 2.axios发送多个请求
  13. // Promise.all
  14. axios.all([
  15. axios.get("/home/multidata"),
  16. // 有完整地址是,baseURL不会生效
  17. axios.get("http://123.207.32.32:9001/lyric?id=500665346")
  18. ]).then(res => { // 只有两个都有结果时,才能调用then
  19. console.log("res:", res)
  20. })

5、axios的创建实例

为什么要创建axios的实例呢?

  • 当我们从axios模块中导入对象时, 使用的实例是默认的实例
  • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.
  • 但是后续开发中, 某些配置可能会不太一样;
  • 比如某些请求需要使用特定的baseURL或者timeout等.
  • 这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.

示例代码

  1. // axios默认库提供给我们的实例对象
  2. axios.get("http://123.207.32.32:9001/lyric?id=500665346")
  3. // 创建其他的实例发送网络请求
  4. const instance1 = axios.create({
  5. baseURL: "http://123.207.32.32:9001",
  6. timeout: 6000,
  7. headers: {}
  8. })
  9. instance1.get("/lyric", {
  10. params: {
  11. id: 500665346
  12. }
  13. }).then(res => {
  14. console.log("res:", res.data)
  15. })
  16. const instance2 = axios.create({
  17. baseURL: "http://123.207.32.32:8000",
  18. timeout: 10000,
  19. headers: {}
  20. })

6、请求和响应拦截器

axios的也可以设置拦截器:拦截每次请求和响应

  • axios.interceptors.request.use(请求成功拦截, 请求失败拦截)
  • axios.interceptors.response.use(响应成功拦截, 响应失败拦截)

代码示例

  1. // 对实例配置拦截器
  2. axios.interceptors.request.use((config) => {
  3. console.log("请求成功的拦截")
  4. // 1.开始loading的动画
  5. // 2.对原来的配置进行一些修改
  6. // 2.1. header
  7. // 2.2. 认证登录: token/cookie
  8. // 2.3. 请求参数进行某些转化
  9. return config
  10. }, (err) => {
  11. console.log("请求失败的拦截")
  12. return err
  13. })
  14. axios.interceptors.response.use((res) => {
  15. console.log("响应成功的拦截")
  16. // 1.结束loading的动画
  17. // 2.对数据进行转化, 再返回数据
  18. return res.data
  19. }, (err) => {
  20. console.log("响应失败的拦截:", err)
  21. return err
  22. })
  23. axios.get("http://123.207.32.32:9001/lyric?id=500665346").then(res => {
  24. console.log("res:", res)
  25. }).catch(err => {
  26. console.log("err:", err)
  27. })

7、axios发起GET请求

axios 发起 get 请求的语法:

axios.get('url', { params: { /*参数*/ } }).then(callback)

具体的请求示例如下:

  1. // 请求的 URL 地址
  2. var url = 'http://www.liulongbin.top:3006/api/get'
  3. // 请求的参数对象
  4. var paramsObj = { name'zs'age20 }
  5. // 调用 axios.get() 发起 GET 请求
  6. axios.get(url, { params: paramsObj }).then(function(res) {
  7. // res.data 是服务器返回的数据
  8. var result = res.data
  9. console.log(res)
  10. })

8、axios发起POST请求

axios 发起 post 请求的语法:

axios.post('url', { /*参数*/ }).then(callback)

具体的请求示例如下:

  1. // 请求的 URL 地址
  2. var url = 'http://www.liulongbin.top:3006/api/post'
  3. // 要提交到服务器的数据
  4. var dataObj = { location'北京'address'顺义' }
  5. // 调用 axios.post() 发起 POST 请求
  6. axios.post(url, dataObj).then(function(res) {
  7. // res.data 是服务器返回的数据
  8. var result = res.data
  9. console.log(result)
  10. })

9、直接使用axios发起请求

axios 也提供了类似于 jQuery $.ajax() 的函数,语法如下:

 axios({

     method: '请求类型',

     url: '请求的URL地址',

     data: { /* POST数据 */ },

     params: { /* GET参数 */ }

 }) .then(callback)

(1)直接使用axios发起GET请求

  1. axios({
  2. method'GET',
  3. url'http://www.liulongbin.top:3006/api/get',
  4. params: { // GET 参数要通过 params 属性提供
  5. name'zs',
  6.          age20
  7.      }
  8. }).then(function(res) {
  9. console.log(res.data)
  10. })

(2)直接使用axios发起POST请求

  1. axios({
  2. method'POST',
  3. url'http://www.liulongbin.top:3006/api/post',
  4. data: { // POST 数据要通过 data 属性提供
  5. bookname'程序员的自我修养',
  6.          price666
  7.      }
  8. }).then(function(res) {
  9. console.log(res.data)
  10. })

10、完整代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <script src="./lib/axios.js"></script>
  9. </head>
  10. <body>
  11. <button id="btn1">发起GET请求</button>
  12. <button id="btn2">发起POST请求</button>
  13. <button id="btn3">直接使用axios发起GET请求</button>
  14. <button id="btn4">直接使用axios发起POST请求</button>
  15. <script>
  16. document.querySelector('#btn1').addEventListener('click', function () {
  17. var url = 'http://www.liulongbin.top:3006/api/get'
  18. var paramsObj = { name: 'zs', age: 20 }
  19. axios.get(url, { params: paramsObj }).then(function (res) {
  20. console.log(res.data)
  21. })
  22. })
  23. document.querySelector('#btn2').addEventListener('click', function () {
  24. var url = 'http://www.liulongbin.top:3006/api/post'
  25. var dataObj = { address: '北京', location: '顺义区' }
  26. axios.post(url, dataObj).then(function (res) {
  27. console.log(res.data)
  28. })
  29. })
  30. document.querySelector('#btn3').addEventListener('click', function () {
  31. var url = 'http://www.liulongbin.top:3006/api/get'
  32. var paramsData = { name: '钢铁侠', age: 35 }
  33. axios({
  34. method: 'GET',
  35. url: url,
  36. params: paramsData
  37. }).then(function (res) {
  38. console.log(res.data)
  39. })
  40. })
  41. document.querySelector('#btn4').addEventListener('click', function () {
  42. axios({
  43. method: 'POST',
  44. url: 'http://www.liulongbin.top:3006/api/post',
  45. data: {
  46. name: '娃哈哈',
  47. age: 18,
  48. gender: '女'
  49. }
  50. }).then(function (res) {
  51. console.log(res.data)
  52. })
  53. })
  54. </script>
  55. </body>
  56. </html>

11、axios请求库封装(简洁版)

封装axios类,index.js

  1. import axios from 'axios'
  2. class HYRequest {
  3. constructor(baseURL, timeout=10000) {
  4. this.instance = axios.create({
  5. baseURL,
  6. timeout
  7. })
  8. }
  9. request(config) {
  10. return new Promise((resolve, reject) => {
  11. this.instance.request(config).then(res => {
  12. resolve(res.data)
  13. }).catch(err => {
  14. reject(err)
  15. })
  16. })
  17. }
  18. get(config) {
  19. return this.request({ ...config, method: "get" })
  20. }
  21. post(config) {
  22. return this.request({ ...config, method: "post" })
  23. }
  24. }
  25. export default new HYRequest("http://123.207.32.32:9001")

main.js中测试

  1. import {createApp} from 'vue'
  2. import axios from 'axios'
  3. import App from './App.vue'
  4. import hyRequest from './service'
  5. createApp(App).mount('#app')
  6. // ==========测试===========
  7. hyRequest.request({
  8. url: "/lyric?id=500665346"
  9. }).then(res => {
  10. console.log("res:", res)
  11. })
  12. hyRequest.get({
  13. url: "/lyric",
  14. params: {
  15. id: 500665346
  16. }
  17. }).then(res => {
  18. console.log("res:", res)
  19. })
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/784034
推荐阅读
相关标签
  

闽ICP备14008679号