Some understanding of apI packaging and building, registration and login in vue about tokens

1. API package

In src Under the new API folder
1. Configure axios in index.js in:

var instances = null;
// 创建一个带自定义配置项的axios 实例
const instance = axios.create({
    
    
  // 所有请求的路径之前都会拼接地址
  baseURL: "url",
  // 延时时间
  timeout: "5000",
  // 请求头设置
  headers: {
    
     "X-Custom-Header": "foobar" },
});

2. Create a new file constants.js to save the request address and method


// 定义常量
const API = {
    
    
    METHODS:{
    
    
        POST:'post',
        GET:'get',
    },
    PATH:{
    
    
        LOGIN:"url",
    }
}
// 导出
export default API;

3. Request interception and response interception

import Loading from "../components/loading/index";
//引入loading组件
import API from "./constants";
//引入定义的常量
instance.interceptors.request.use(
  (config) => {
    
    
    // 发送请求成功做出的操作
    // 弹出loading(加载中)控件
    console.log(Loading);
    instances = Loading.serve.open();
    // 拦截请求config配置 动态添加或者删除配置
    return config;
  },
  (err) => {
    
    
    //   console.log(err)
    // 发送请求错误 对请求出错的操作
    //
    // 提示用户请求失败并返回发送失败原因
    return Promise.reject(err);
  }
);
//axios设置响应拦截器
instance.interceptors.response.use(
  (response) => {
    
    
    // 响应成功 对响应数据进行处理
    // 根据请求的服务器所响应的状态码进行对客户端的响应
    // 收起loading控件
    instances = Loading.serve.close();
    // 拦截处理响应结果,直接返回需要的数据
    return response.data;
  },
  (err) => {
    
    
    // 处理响应失败的数据
    return Promise.reject(err);
  }
);

4. How to encapsulate the request

// 封装请求的方法 导出
export function request(method, url, params) {
    
    
  switch (method) {
    
    
    case API.METHODS.POST:
      return post(url, params);
    case API.METHODS.GET:
      return get(url, params);
  }
}

5. Method of configuring request path

// 最终的接口文件 
// 引入配置
import {
    
    request} from "./core";
// 引入请求方法和路径
import API from './constants';
const APIClient = {
    
    
    // 登录方法
    login(username,password){
    
    
        return request(API.METHODS.POST,API.PATH.LOGIN,{
    
    username:username,password:password})
    },
 }
// 导出
export default APIClient;

API usage

The configuration in the main.js file is as follows
javascript

// 配置api请求
import APIClient from "./API/index";
// 放入原型以供调用
Vue.prototype.$APIClient = APIClient;

Just call the encapsulated function when using it

  mounted() {
    
    
 	// 调用函数
    this.$APIClient.login().then((res) => {
    
    
    // 保存请求成功的数据
      this.cates = res.data;
    });
  },

APP login

1.token

在计算机身份认证中是令牌(临时)的意思,在词法分析中是标记的意思。一般作为邀请、登录系统使用。主要作用是确认用户的身份,帮助用户保护个人信息。

It is very simple to use, just save the token returned by the background to the local when sending the login request.

window.sessionStorage.setItem("token", data.data.remember_token);

Generally used sessionStorage is more secure than localStorage

2. Token verification After
obtaining the token, it is necessary to verify the local token verification in the request interception, and store it in the request header if it exists

serve.interceptors.request.use((config) => {
    
    
    // token验证请求
    let token = JSON.parse(window.sessionStorage.getItem("token"))
    if(token){
    
    
        config.headers.Authorization = `Bearer ${
      
      token}`
    }
    config.headers.deviceid = deviceid;
    config.headers.devicetype = "H5";
    return config
})

When the user is not logged in, it needs to be forced to jump to the login page to log in. Use the routing hook to jump

if (!window.sessionStorage.getItem("token")) {
    
    
      next("/Login")
  }

Guess you like

Origin blog.csdn.net/t5_5_5_5_5_7_7/article/details/109433830