赞
踩
功能特点:
支持多种请求方式:
- axios(config)
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
有时候, 我们可能需求同时发送两个请求
参数 | 说明 |
请求地址 | 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){}], |
- // 1.发送request请求
- axios.request({
- url: "http://123.207.32.32:8000/home/multidata",
- method: "get"
- }).then(res => {
- console.log("res:", res.data)
- })
-
- // 2.发送get请求
- axios.get(`http://123.207.32.32:9001/lyric?id=500665346`).then(res => {
- console.log("res:", res.data.lrc)
- })
- axios.get("http://123.207.32.32:9001/lyric", {
- params: {
- id: 500665346
- }
- }).then(res => {
- console.log("res:", res.data.lrc)
- })
-
-
- // 3.发送post请求
- axios.post("http://123.207.32.32:1888/02_param/postjson", {
- name: "coderwhy",
- password: 123456
- }).then(res => {
- console.log("res", res.data)
- })
-
- axios.post("http://123.207.32.32:1888/02_param/postjson", {
- data: {
- name: "coderwhy",
- password: 123456
- }
- }).then(res => {
- console.log("res", res.data)
- })
-

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

为什么要创建axios的实例呢?
示例代码
- // axios默认库提供给我们的实例对象
- axios.get("http://123.207.32.32:9001/lyric?id=500665346")
-
- // 创建其他的实例发送网络请求
- const instance1 = axios.create({
- baseURL: "http://123.207.32.32:9001",
- timeout: 6000,
- headers: {}
- })
-
- instance1.get("/lyric", {
- params: {
- id: 500665346
- }
- }).then(res => {
- console.log("res:", res.data)
- })
-
- const instance2 = axios.create({
- baseURL: "http://123.207.32.32:8000",
- timeout: 10000,
- headers: {}
- })

axios的也可以设置拦截器:拦截每次请求和响应
代码示例
- // 对实例配置拦截器
- axios.interceptors.request.use((config) => {
- console.log("请求成功的拦截")
- // 1.开始loading的动画
-
- // 2.对原来的配置进行一些修改
- // 2.1. header
- // 2.2. 认证登录: token/cookie
- // 2.3. 请求参数进行某些转化
-
- return config
- }, (err) => {
- console.log("请求失败的拦截")
- return err
- })
-
- axios.interceptors.response.use((res) => {
- console.log("响应成功的拦截")
-
- // 1.结束loading的动画
-
- // 2.对数据进行转化, 再返回数据
- return res.data
- }, (err) => {
- console.log("响应失败的拦截:", err)
- return err
- })
-
- axios.get("http://123.207.32.32:9001/lyric?id=500665346").then(res => {
- console.log("res:", res)
- }).catch(err => {
- console.log("err:", err)
- })

axios 发起 get 请求的语法:
axios.get('url', { params: { /*参数*/ } }).then(callback)
具体的请求示例如下:
- // 请求的 URL 地址
- var url = 'http://www.liulongbin.top:3006/api/get'
- // 请求的参数对象
- var paramsObj = { name: 'zs', age: 20 }
- // 调用 axios.get() 发起 GET 请求
- axios.get(url, { params: paramsObj }).then(function(res) {
- // res.data 是服务器返回的数据
- var result = res.data
- console.log(res)
- })
axios 发起 post 请求的语法:
axios.post('url', { /*参数*/ }).then(callback)
具体的请求示例如下:
- // 请求的 URL 地址
- var url = 'http://www.liulongbin.top:3006/api/post'
- // 要提交到服务器的数据
- var dataObj = { location: '北京', address: '顺义' }
- // 调用 axios.post() 发起 POST 请求
- axios.post(url, dataObj).then(function(res) {
- // res.data 是服务器返回的数据
- var result = res.data
- console.log(result)
- })
axios 也提供了类似于 jQuery 中 $.ajax() 的函数,语法如下:
axios({
method: '请求类型',
url: '请求的URL地址',
data: { /* POST数据 */ },
params: { /* GET参数 */ }
}) .then(callback)
(1)直接使用axios发起GET请求
- axios({
- method: 'GET',
- url: 'http://www.liulongbin.top:3006/api/get',
- params: { // GET 参数要通过 params 属性提供
- name: 'zs',
- age: 20
- }
- }).then(function(res) {
- console.log(res.data)
- })
(2)直接使用axios发起POST请求
- axios({
- method: 'POST',
- url: 'http://www.liulongbin.top:3006/api/post',
- data: { // POST 数据要通过 data 属性提供
- bookname: '程序员的自我修养',
- price: 666
- }
- }).then(function(res) {
- console.log(res.data)
- })
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Document</title>
- <script src="./lib/axios.js"></script>
- </head>
-
- <body>
- <button id="btn1">发起GET请求</button>
- <button id="btn2">发起POST请求</button>
- <button id="btn3">直接使用axios发起GET请求</button>
- <button id="btn4">直接使用axios发起POST请求</button>
-
- <script>
- document.querySelector('#btn1').addEventListener('click', function () {
- var url = 'http://www.liulongbin.top:3006/api/get'
- var paramsObj = { name: 'zs', age: 20 }
- axios.get(url, { params: paramsObj }).then(function (res) {
- console.log(res.data)
- })
- })
-
- document.querySelector('#btn2').addEventListener('click', function () {
- var url = 'http://www.liulongbin.top:3006/api/post'
- var dataObj = { address: '北京', location: '顺义区' }
- axios.post(url, dataObj).then(function (res) {
- console.log(res.data)
- })
- })
-
- document.querySelector('#btn3').addEventListener('click', function () {
- var url = 'http://www.liulongbin.top:3006/api/get'
- var paramsData = { name: '钢铁侠', age: 35 }
- axios({
- method: 'GET',
- url: url,
- params: paramsData
- }).then(function (res) {
- console.log(res.data)
- })
- })
-
- document.querySelector('#btn4').addEventListener('click', function () {
- axios({
- method: 'POST',
- url: 'http://www.liulongbin.top:3006/api/post',
- data: {
- name: '娃哈哈',
- age: 18,
- gender: '女'
- }
- }).then(function (res) {
- console.log(res.data)
- })
- })
- </script>
- </body>
-
- </html>

封装axios类,index.js
- import axios from 'axios'
-
- class HYRequest {
- constructor(baseURL, timeout=10000) {
- this.instance = axios.create({
- baseURL,
- timeout
- })
- }
-
- request(config) {
- return new Promise((resolve, reject) => {
- this.instance.request(config).then(res => {
- resolve(res.data)
- }).catch(err => {
- reject(err)
- })
- })
- }
-
- get(config) {
- return this.request({ ...config, method: "get" })
- }
-
- post(config) {
- return this.request({ ...config, method: "post" })
- }
- }
-
- export default new HYRequest("http://123.207.32.32:9001")
-

main.js中测试
- import {createApp} from 'vue'
- import axios from 'axios'
- import App from './App.vue'
- import hyRequest from './service'
-
- createApp(App).mount('#app')
-
- // ==========测试===========
-
- hyRequest.request({
- url: "/lyric?id=500665346"
- }).then(res => {
- console.log("res:", res)
- })
-
- hyRequest.get({
- url: "/lyric",
- params: {
- id: 500665346
- }
- }).then(res => {
- console.log("res:", res)
- })

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。