axios从入门到源码分析 -http-xhr

2 篇文章 0 订阅

axios从入门到源码分析

1 HTTP相关

1.1.MDN文档

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Overview

1.2. HTTP请求交互的基本过程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e9jqRug7-1621944040739)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps1.jpg)]

  1. 前台应用从浏览器端向服务器发送HTTP请求(请求报文)

  2. 后台服务器接收到请求后, 调度服务器应用处理请求, 向浏览器端返回HTTP响应(响应报文)

  3. 浏览器端接收到响应, 解析显示响应体/保存数据并调用监视回调

1.3. HTTP请求报文

1. 请求行:

method url

GET /product_detail?id=2

POST /login

2. 请求头(多个)

Host: www.baidu.com

Cookie: BAIDUID=AD3B0FA706E; BIDUPSID=AD3B0FA706;

Content-Type: application/x-www-form-urlencoded 或者 application/json

**3.**请求体

urlencoded格式: username=tom&pwd=123

json格式: {“username”: “tom”, “pwd”: 123}

1.4. HTTP响应报文

**1.**响应行:

status statusText

200 OK

404 Not Found

2. 响应头(多个)

Content-Type: text/html;charset=utf-8 text/json;charset=utf-8

Set-Cookie: BD_CK_SAM=1;path=/

3. 响应体

html文本/json文本/js/css/图片…

1.5. post请求体参数格式

  1. Content-Type: application/x-www-form-urlencoded;charset=utf-8

用于键值对参数,参数的键值用=连接, 参数之间用&连接

例如: name=%E5%B0%8F%E6%98%8E&age=12

  1. Content-Type: application/json;charset=utf-8

用于json字符串参数

例如: {“name”: “%E5%B0%8F%E6%98%8E”, “age”: 12}

  1. Content-Type: multipart/form-data

用于文件上传请求

1.6. 常见的响应状态码

200 OK 请求成功。一般用于GET与POST请求

201 Created 已创建。成功请求并创建了新的资源

401 Unauthorized 未授权/请求要求用户的身份认证

404 Not Found 服务器无法根据客户端的请求找到资源

500 Internal Server Error 服务器内部错误,无法完成请求

1.7. 不同类型的请求及其作用

  1. GET: 从服务器端读取数据

  2. POST: 向服务器端添加新数据

  3. PUT: 更新服务器端数据 (完整更新数据)

  4. PATCH: 更新服务器数据 (局部更新数据)

  5. DELETE: 删除服务器端数据

1.8. 使用postman测试API

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FLL4D5ss-1621944040742)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps2.jpg)]

1.9. API的分类

1.9.1. REST(restful) API /weibo get post put delete

  1. 发送请求进行CRUD哪个操作由请求方式来决定

  2. 同一个请求路径可以进行多个操作

  3. 请求方式会用到GET/POST/PUT/DELETE

1.9.2. 非REST(restless) API

  1. 请求方式不决定请求的CRUD操作

  2. 一个请求路径只对应一个操作

  3. 一般只有GET/POST

1.10. 使用json-server搭建REST API

1.10.1. json-server是什么?

用来快速搭建模拟的REST API的工具包

1.10.2. 使用json-server

  1. 在线文档: https://github.com/typicode/json-server

  2. https://blog.csdn.net/u012149969/article/details/108394159

  3. 下载: npm install -g json-server

    安装: json-server -v

  4. 目标根目录下创建数据库json文件: data.json

{
   "scoreList":[
     {"id":1,"userName":"张三","age":12,"sex":"男","score":{"yuWen":10,"shuXue":20,"yingYu":30}},
     {"id":2,"userName":"李四","age":21,"sex":"女","score":{"yuWen":12,"shuXue":45,"yingYu":37}},
     {"id":3,"userName":"王五","age":56,"sex":"男","score":{"yuWen":12,"shuXue":20,"yingYu":30}},
     {"id":4,"userName":"赵六","age":23,"sex":"女","score":{"yuWen":19,"shuXue":21,"yingYu":65}},
     {"id":5,"userName":"严七","age":12,"sex":"男","score":{"yuWen":34,"shuXue":67,"yingYu":43}},
     {"id":6,"userName":"沈八","age":43,"sex":"女","score":{"yuWen":56,"shuXue":76,"yingYu":30}},
     {"id":7,"userName":"钱九","age":13,"sex":"男","score":{"yuWen":24,"shuXue":89,"yingYu":30}},
     {"id":8,"userName":"张十","age":12,"sex":"女","score":{"yuWen":10,"shuXue":54,"yingYu":31}}
   ]
 }

  1. 启动服务器执行命令:

    不会实时检测数据变化

json-server data.json

​ 会实时检测数据变化 3000是默认端口号,localhost可以更改

  • – watch:通过该命令可以实时监测score.json的变化,如果省略该命令,即使score.json发生变化,刷新、或重新发送请求,仍然会返回初次启动服务时的数据。简写形式为:-w
    –port:指定服务的端口号,可省略,默认为3000。简写形式:-p
    –host:设置域,可省略。简写形式:-h
json-server --watch data.json
json-server score.json -w -p 8090 -H 127.0.0.1

1.10.3. 使用浏览器访问测试

http://localhost:3000/posts

http://localhost:3000/posts/1

1.10.4. 使用postman测试接口

测试GET / POST / PUT / DELETE请求

2 XHR的理解和使用

2.1. MDN文档

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

2.2. 理解

  1. 使用XMLHttpRequest (XHR)对象可以与服务器交互, 也就是发送ajax请求

  2. 前端可以获取到数据,而无需让整个的页面刷新。

  3. 这使得Web页面可以只更新页面的局部,而不影响用户的操作。

2.3. 区别一般http请求与ajax请求

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0t0Ney7G-1621944040744)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps3.jpg)]

  1. ajax请求是一种特别的http请求

  2. 对服务器端来说, 没有任何区别, 区别在浏览器端

  3. 浏览器端发请求: 只有XHR或fetch发出的才是ajax请求, 其它所有的都是非ajax请求

  4. 浏览器端接收到响应

    (1) 一般请求: 浏览器一般会直接显示响应体数据, 也就是我们常说的刷新/跳转页面

    (2) ajax请求: 浏览器不会对界面进行任何更新操作, 只是调用监视的回调函数并传入响应相关数据

fetch:是window下的函数,返回值是一个promise

使用get,post ,put,put,patch,delete

get获取scoreList fetch
 	const btns = document.querySelectorAll("button");
        btns[0].onclick = function() {
            const xhr = new XMLHttpRequest();
            xhr.open("get","http://127.0.0.1:3000/scoreList?id=1");
            xhr.send();
            xhr.onload = function() {
                console.log(xhr.responseText)
            }
        }
 btns[0].onclick = function() {
     //第一种获得fetch
            fetch("http://127.0.0.1:3000/scoreList")
            .then(value=>{
                return value.json()     //以对象的形式返回
                //return value.text()   //以文本的形式返回
            }).then(value=>{
                console.log(value)
            })
     
     //第二种获得fetch
     const res = await fetch("http://127.0.0.1:3000/scoreList")
            const value = await res.json()
            console.log(value)
     
     //第三种
     const res = fetch("http://127.0.0.1:3000/scoreList").then(value=>{
                return value.json()
            })
            res.then(value=> {
                console.log(value)
            })
     
     //第四种
    const res = await fetch("http://127.0.0.1:3000/scoreList").then (value=>{
                return value.json()
            })
         console.log(res)
 }
post添加数据 fetch
		btns[1].onclick = function() {
            const xhr = new XMLHttpRequest();
            // 数据格式为application/json
            xhr.open("post","http://127.0.0.1:3000/scoreList")
            // xhr.setRequestHeader("content-type","application/json")
            // xhr.send(JSON.stringify({
            //     a:3,
            //     b:4
            // }))
            // xhr.onload = function() {
            //     console.log(xhr.responseText)
            // }
            // 数据格式为x-www-form-urlencoded
            xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
            xhr.send("c=5&d=6");
            xhr.onload = function() {
                console.log(xhr.responseText)
            }  
        }
const res = await fetch("http://127.0.0.1:3000/scoreList",{
                method:"post",
                headers:{
                    "content-type":"application/x-www-form-urlencoded"
                },
                body:"a=1&b=2"
            }).then(value=>{
                return value.json()
            })
            console.log(res)
put更新数据(完整) fetch
 btns[2].onclick = function () {
        const xhr = new XMLHttpRequest();
        xhr.open("put","http://127.0.0.1/scoreList/10");
        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
        xhr.send("c=1&d=2&userName=黎明");
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
    }
 btns[2].onclick = async  function () {
        fetch("http://127.0.0.1/scoreList/3",{
            method:"put",
            headers:{
                "content-type":"application/x-www-form-urlencoded"
            },
            body:"hobby=学习"
        }).then(value=>value.json()).then(res=>console.log(res));
    }
delete删除数据 fetch
btns[3].onclick = function () {
        const xhr = new XMLHttpRequest();
        xhr.open("delete","http://127.0.0.1/scoreList/9");
        xhr.send();
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
    }
btns[3].onclick = async function f() {
        fetch("http://127.0.0.1/scoreList/3",{
            method:"delete"
        }).then(value=>value.json()).then(res=>console.log(res));
    }
patch更新数据(局部) fetch
btns[4].onclick = function () {
        const xhr = new XMLHttpRequest();
        xhr.open("PATCH","http://127.0.0.1/scoreList/8");
        xhr.setRequestHeader("content-type","application/json")
        xhr.send(JSON.stringify({
            userName:"张天师"
        }));
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
    }
 btns[4].onclick = async function f() {
        fetch("http://127.0.0.1/scoreList/4",{
            method:"PATCH",
            headers:{
                "content-type":"application/json"
            },
            body:JSON.stringify({
                userName:"孙悟空"
            })
        }).then(value=>value.json()).then(res=>console.log(res));
    }

2.4. API

  1. XMLHttpRequest(): 创建XHR对象的构造函数

  2. status: 响应状态码值, 比如200, 404

  3. statusText: 响应状态文本

  4. readyState: 标识请求状态的只读属性

    0: 初始

    1: open()之后

    2: send()之后

    3: 请求中

    4: 请求完成

  5. onreadystatechange: 绑定readyState改变的监听

  6. responseType: 指定响应数据类型, 如果是’json’, 得到响应后自动解析响应体数据

  7. response: 响应体数据, 类型取决于responseType的指定

  8. timeout: 指定请求超时时间, 默认为0代表没有限制

  9. ontimeout: 绑定超时的监听

  10. onerror: 绑定请求网络错误的监听

  11. open(): 初始化一个请求, 参数为: (method, url[, async])

  12. send(data): 发送请求

  13. abort(): 中断请求

  14. getResponseHeader(name): 获取指定名称的响应头值

  15. getAllResponseHeaders(): 获取所有响应头组成的字符串

  16. setRequestHeader(name, value): 设置请求头

2.5. 使用axios发ajax请求

2.6. XHR的基本使用

  1. 创建XHR对象

  2. 打开连接

  3. 绑定状态改变的监听, 并在异步回调中读取响应数据

  4. 发送请求

2.7. XHR的ajax封装(简单版axios)

2.7.1. 特点

  1. 函数的返回值为promise, 成功的结果为response, 异常的结果为error

  2. 能处理多种类型的请求: GET/POST/PUT/DELETE

  3. 函数的参数为一个配置对象

{
url: '',  // 请求地址
method: '',  // 请求方式GET/POST/PUT/DELETE
params: {},  // GET/DELETE请求的query参数
data: {}, // POST或PUT请求的请求体参数 
}
  1. 响应json数据自动解析为js

2.7.2. 编码实现

/*
    使用XHR封装发送ajax请求的通用函数
      返回值: promise
      参数为配置对象
        url: 请求地址
    params: 包含所有query请求参数的对象 {name: tom, age: 12} ==> name=tom&age=12
        data: 包含所有请求体参数数据的对象
        method: 为请求方式
    */
    function axios({url, method='GET', params={}, data={}}) {

      method = method || 'GET'
      method = method.toUpperCase()
      // 将params中的参数属性拼接到url上   
      // {name: tom: pwd: 123}  ===> queryStr=name=tom&pwd=123
      // url + ? + queryStr
      let queryStr = ''
      Object.keys(params).forEach(key => {
        // &pwd=123
          queryStr += '&' + key + '=' + params[key]
      })
      // '&name=tom&pwd=123' 或者 ''
      if (queryStr) {
        queryStr = queryStr.substring(1) // 'name=tom&pwd=123'
        url += '?' + queryStr  // /user?name=tom&pwd=123
      }
      
      return new Promise((resolve, reject) => {
        // 创建XHR对象
        const request = new XMLHttpRequest()
        // 打开连接(初始化请求对象)
        request.open(method, url, true)
        // 设置响应数据类型 ==> 自动解析json文本为js对象/数组, 保存给response属性上
        request.responseType = 'json'
        // 绑定监视request的状态改变的监听
        request.onreadystatechange = function () {
          // 如果请求还没有完成, 直接结束
          if (request.readyState!==4) {
            return
          }
          const {status, statusText} = request
          // 如果成功了, 取出数据封装成成功的响应数据对象response, 调用resolve(response)
          if (status>=200 && status<300) { // 在[200, 300)
            const response = {
              // data: JSON.parse(request.response),
              data: request.response,
              status,
              statusText
            }
            resolve(response)
          } else {
             // 如果失败了, 封装失败相关信息成error对象, 调用reject(error)
             reject(new Error('request error status is ' + status))
          }
        }
        if (method==='GET' || method==='DELETE') {
          // 发送请求
          request.send()
        } else { // POST/PUT
          // 设置请求头
          request.setRequestHeader('Content-Type', 'application/json;charset=utf-8')
          // 发送请求
          request.send(JSON.stringify(data))
        }
      })
    }

2.7.3. 使用测试

function testGet() {
      axios({
        url: 'http://localhost:3000/comments',
        // url: 'http://localhost:3000/comments2',
        params: {id: 3},
      }).then(response => {
        console.log('get success', response.data, response)
      }).catch(error => {
        alert(error.message)
      })
    }

    function testPost() {
      axios({
        url: 'http://localhost:3000/comments',
        // url: 'http://localhost:3000/comments2',
        method: 'POST',
        data: { body: 'aaaa', postId: 2 }
      }).then(response => {
        console.log('post success', response.data, response)
      }).catch(error => {
        alert(error.message)
      })
}

    function testPut() {
      axios({
        url: 'http://localhost:3000/comments/3',
        // url: 'http://localhost:3000/comments/39',
        method: 'put',
        data: {body: 'abcdefg', "postId": 2}
      }).then(response => {
        console.log('put success', response.data, response)
      }).catch(error => {
        alert(error.message)
      })
    }
    
    function testDelete() {
      axios({
        url: 'http://localhost:3000/comments/1',
        method: 'delete',
        params: {
          body: 'some comment'
        }
      }).then(response => {
        console.log('delete success', response.data, response)
      }).catch(error => {
        alert(error.message)
      })
    }

3 axios的理解和使用

引入:npm init -y

安装:npm install axios

3.1. axios是什么?

  1. 前端最流行的ajax请求库

  2. react/vue官方都推荐使用axios发ajax请求

  3. 文档: https://github.com/axios/axios

3.2. axios特点

  1. 基于xhr + promise的异步ajax请求库

  2. 浏览器端/node端都可以使用

  3. 支持请求/响应拦截器

  4. 支持请求取消

  5. 请求/响应数据转换

  6. 批量发送多个请求

3.3. axios常用语法

axios(config): 通用/最本质的发任意类型请求的方式

axios(url[, config]): 可以只指定url发get请求

axios.request(config): 等同于axios(config)

axios.get(url[, config]): 发get请求

axios.delete(url[, config]): 发delete请求

axios.post(url[, data, config]): 发post请求

axios.put(url[, data, config]): 发put请求

axios.defaults.xxx: 请求的默认全局配置

axios.interceptors.request.use(): 添加请求拦截器

axios.interceptors.response.use(): 添加响应拦截器

axios.create([config]): 创建一个新的axios(它没有下面的功能)

axios.Cancel(): 用于创建取消请求的错误对象

axios.CancelToken(): 用于创建取消请求的token对象

axios.isCancel(): 是否是一个取消请求的错误

axios.all(promises): 用于批量执行多个异步请求

axios.spread(): 用来指定接收所有成功数据的回调函数的方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yH3Q1mAF-1621944040746)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps4.png)]

3.4. 难点语法的理解和使用

3.4.1. axios.create(config)

  1. 根据指定配置创建一个新的axios, 也就就每个新axios都有自己的配置

  2. 新axios只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的

  3. 为什么要设计这个语法?

(1) 需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一样, 如何处理

(2) 解决: 创建2个新axios, 每个都有自己特有的配置, 分别应用到不同要求的接口请求中

拦截器函数/ajax请求/请求的回调函数的调用顺序

  1. 说明: 调用axios()并不是立即发送ajax请求, 而是需要经历一个较长的流程

  2. 流程: 请求拦截器2 => 请求拦截器1 => 发ajax请求 => 响应拦截器1 => 响应拦截器2 => 请求的回调

  3. 注意: 此流程是通过promise串连起来的, 请求拦截器传递的是config, 响应拦截器传递的是response

3.4.2. 取消请求

  1. 基本流程

    配置cancelToken对象

    缓存用于取消请求的cancel函数

    在后面特定时机调用cancel函数取消请求

    在错误回调中判断如果error是cancel, 做相应处理

  2. 实现功能

    点击按钮, 取消某个正在请求中的请求

    在请求一个接口前, 取消前面一个未完成的请求

4 axios源码分析

4.1. 源码目录结构

4.2. [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jQlyzp1b-1621944040747)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps5.png)]源码分析

4.2.1. axios与Axios的关系?

  1. 从语法上来说: axios不是Axios的实例

  2. 从功能上来说: axios是Axios的实例

  3. axios是Axios.prototype.request函数bind()返回的函数

  4. axios作为对象有Axios原型对象上的所有方法, 有Axios对象上所有属性

4.2.2. instance与axios的区别?

  1. 相同:

(1) 都是一个能发任意请求的函数: request(config)

(2) 都有发特定请求的各种方法: get()/post()/put()/delete()

(3) 都有默认配置和拦截器的属性: defaults/interceptors

  1. 不同:

(1) 默认配置很可能不一样

(2) instance没有axios后面添加的一些方法: create()/CancelToken()/all()

4.2.3. axios运行的整体流程?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-37Jbg6kF-1621944040749)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps6.png)]

  1. 整体流程:

request(config) ==> dispatchRequest(config) ==> xhrAdapter(config)

  1. request(config):

将请求拦截器 / dispatchRequest() / 响应拦截器 通过promise链串连起来, 返回promise

  1. dispatchRequest(config):

转换请求数据 ===> 调用xhrAdapter()发请求 ===> 请求返回后转换响应数据. 返回promise

  1. xhrAdapter(config):

创建XHR对象, 根据config进行相应设置, 发送特定请求, 并接收响应数据, 返回promise

4.2.4. axios的请求/响应拦截器是什么?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0v5BcYiG-1621944040749)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps7.png)]

  1. 请求拦截器:

在真正发送请求前执行的回调函数

可以对请求进行检查或配置进行特定处理

成功的回调函数, 传递的默认是config(也必须是)

失败的回调函数, 传递的默认是error

  1. 响应拦截器

在请求得到响应后执行的回调函数

可以对响应数据进行特定处理

成功的回调函数, 传递的默认是response

失败的回调函数, 传递的默认是error

4.2.5. axios的请求/响应数据转换器是什么?

  1. 请求转换器: 对请求头和请求体数据进行特定处理的函数

if (utils.isObject(data)) {

setContentTypeIfUnset(headers, ‘application/json;charset=utf-8’);

return JSON.stringify(data);

}

  1. 响应转换器: 将响应体json字符串解析为js对象或数组的函数

response.data = JSON.parse(response.data)

4.2.6. response的整体结构

{

​ data,

​ status,

​ statusText,

​ headers,

​ config,

​ request

}

4.2.7. error的整体结构

{

​ message,

​ response,

request,

}

4.2.8. 如何取消未完成的请求?

  1. 当配置了cancelToken对象时, 保存cancel函数

(1) 创建一个用于将来中断请求的cancelPromise

(2) 并定义了一个用于取消请求的cancel函数

(3) 将cancel函数传递出来

  1. 调用cancel()取消请求

(1) 执行cacel函数, 传入错误信息message

(2) 内部会让cancelPromise变为成功, 且成功的值为一个Cancel对象

(3) 在cancelPromise的成功回调中中断请求, 并让发请求的proimse失败, 失败的reason为Cancel对象

4.3. [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OONneLSj-1621944040750)(file:///C:\Users\王秀\AppData\Local\Temp\ksohtml3944\wps8.png)]Axios二次封装

4.3.1. 功能点

  1. 统一进行请求配置: 基础路径/超时时间等

  2. 请求过程中loading提示

  3. 请求可能需要携带token数据

  4. 请求成功的value不再是response, 而是response.data

  5. 请求失败/出错统一进行处理, 每个请求可以不用单独处理

4.3.2. 编码实现与测试

<!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>Axios二次封装</title>
  <link rel="stylesheet" href="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.css">
</head>
<body>

<div>
  <button onclick="getUsers()">获取用户列表</button>
  <button onclick="getRepos()">获取仓库列表</button>
</div>
  
  <!-- 
    测试接口1: https://api.github.com/search/repositories?q=v&sort=stars
    测试接口1: https://api.github.com/search/users?q=v
  -->
  <!--
   1). 统一进行请求配置: 基础路径/超时时间等
   2). 请求过程中loading提示
   3). 请求可能需要携带token数据
   4). 请求成功的value不再是response, 而是response.data
   5). 请求失败/出错统一进行处理, 每个请求可以不用单独处理
  -->

  <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
  <script src="https://cdn.bootcss.com/nprogress/0.2.0/nprogress.js"></script>
  <script>
    const instance = axios.create({
      baseURL: 'https://api.github.com',
      timeout: 15000
    })

    instance.interceptors.request.use(config => {
      NProgress.start()
      // 从local中读取前面保存的token数据
      const token = localStorage.getItem('token_key') || 'xxxxx'
      if (token) {
        config.headers['token'] = token  // 请求头的名称为后台接口指定
      }

      return config
    })

    instance.interceptors.response.use(
      response => {
        NProgress.done()
        return response.data
      },
      error => {
        NProgress.done()
        alert('请求出错了', error)
        return error
      }
    )
  </script>

  <script>
    function getUsers () {
      instance.get('/search/users', {
        params: {
          q: 'v'
        }
      }).then(result => {
        console.table(result.items)
      })
    }

    function getRepos () {
      instance.get('/search/repositories', {
        params: {
          q: 'v',
          sort: 'stars'
        }
      }).then(result => {
        console.table(result.items)
      })
    }
  </script>
</body>
</html>

.start()
// 从local中读取前面保存的token数据
const token = localStorage.getItem(‘token_key’) || ‘xxxxx’
if (token) {
config.headers[‘token’] = token // 请求头的名称为后台接口指定
}

  return config
})

instance.interceptors.response.use(
  response => {
    NProgress.done()
    return response.data
  },
  error => {
    NProgress.done()
    alert('请求出错了', error)
    return error
  }
)
```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值