I’ve covered configuring AXIos with typescript before. That version uses the class syntax, this time introduces the normal writing method of VUe3.0, and finally tests the login interface with eggJS.

Ts, status.ts, and type.ts files are required in the./ SRC/API directory.

├ ─ SRC │ ├ ─ API │ │ ├ ─ API. Ts │ │ ├ ─ status. The ts │ │ └ ─ the tsCopy the code

./src/api/api.ts

import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import qs from 'qs'
import { showMessage } from "./status";
import { ElMessage } from 'element-plus'
import { IResponse, ILogin } from './type';

let axiosInstance:AxiosInstance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL + "/api/v1/".headers: {
    Accept: "application/json"."Content-Type": "application/x-www-form-urlencoded"
  },
  transformRequest: [
    function(data) {
      // Use form-data to transmit data
      delete data.Authorization;
      data = qs.stringify(data);
      returndata; }}]);// The Axios instance intercepts the response
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) = > {
    if (response.headers.authorization) {
      localStorage.setItem('app_token', response.headers.authorization);
    } else {
      if (response.data && response.data.token) {
        localStorage.setItem('app_token', response.data.token); }}if (response.status === 200) {
      return response;
    } else {
      showMessage(response.status);
      returnresponse; }},// The request failed
  (error: any) = > {
    const {response} = error;
    if (response) {
      // The request has been sent, but it is not in the scope of 2xx
      showMessage(response.status);
      return Promise.reject(response.data);
    } else {
      ElMessage.warning(The network connection is abnormal, please try again later! '); }});// The Axios instance intercepts the request
axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) = > {
    // const { user } = store.state
    // if (token) {
    // config.headers.Authorization = `Bearer ${token}`
    // }
    return config;
  },
  (error:any) = > {
    return Promise.reject(error); })/ * * *@description: User login *@params {ILogin} params
 * @return {Promise}* /
export const login = (params: ILogin): Promise<IResponse> => {
  return axiosInstance.post('user/login',params).then(res= > res.data);
};
Copy the code
  • The overall way is to create an instance, by adding request and response interceptors to the instance, do the corresponding processing.
  • axios.createtransformRequestTo configure, delete theAuthorizationAnd then through theqsDependencies convert the Form of the parameters (converting object literals to Form Data format).
  • I did the right thing in response interceptiontokenThe processing of
  • Request header in request interceptionheaderTo give inAuthorizationaddtokenTo be modified based on service requirements.
  • This file creates a login interfaceloginUsed to testeggjsProvided interface.

./src/api/status.ts

export const showMessage = (status:number|string) : string= > {
  let message:string = "";
  switch (status) {
    case 400:
      message = "Request error (400)";
      break;
    case 401:
      message = "Unauthorized, please log in to (401) again";
      break;
    case 403:
      message = "Access denied (403)";
      break;
    case 404:
      message = "Request error (404)";
      break;
    case 408:
      message = "Request timeout (408)";
      break;
    case 500:
      message = "Server error (500)";
      break;
    case 501:
      message = "Service not implemented (501)";
      break;
    case 502:
      message = Network error (502);
      break;
    case 503:
      message = "Service unavailable (503)";
      break;
    case 504:
      message = "Network timeout (504)";
      break;
    case 505:
      message = "HTTP version not supported (505)";
      break;
    default:
      message = 'Connection error (${status})! `;
  }
  return `${message}, please check the network or contact the administrator! `;
};
Copy the code
  • Status. ts Returns the message text corresponding to the status.

./src/api/type.ts

// Return the interface of res.data
export interface IResponse {
  code: number | string;
  data: any;
  msg: string;
}

/** User login */
export interface ILogin {
  /** Account name */
  username: string;
  /** Account password */
  password: string;
}
Copy the code
  • The type.ts set defines variousapiRelated interfaces. If there are too many interfaces in the future, this file may be very bloated, if there are other ways to optimize the folder directory, welcome to discuss.

/ SRC /views/ home.vue

import { defineComponent, onMounted } from 'vue';
import { login } from '@/api/api';
export default defineComponent({
  name: 'Home'.setup() {
  	onMounted(() = >{
      login({
  		username:'admin'.password:'123456'}); }}}));Copy the code

Finally, the interface provided by EGGJS is invoked. There is no much introduction about EGGJS here, and it is not complicated to write a demo according to the official documents.

  • eggjsloginInterface Address Yeshttp://localhost:7001/api/v1/user/login
  • My env configuration fileVUE_APP_BASE_URL 是 http://0.0.0.0:7001. This allows the interface to be invoked.

The data returned by the interface is processed by./ SRC/API /api.ts. The res.data result is as follows:

{
  "code": 200."msg": "Login successful"."data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNvbmljIiwiaWF0IjoxNjE4OTc0NDQzfQ.XtKLR2_AHFq0r5we71V7BWVtXvQLeYu 2OGYv-w8iZEM"}}Copy the code