vue calls RESTful style interface operations

  • 2021-08-06 20:21:31
  • OfStack

The first is the simple java interface code

I wrote four interfaces for the front-end request. The following is the code


  @GetMapping("/v1/user/{username}/{password}")
  public Result login2(@PathVariable("username") String username, @PathVariable("password") String password){
    return Result.succResult(200,username+"--"+password);
  }
 
  @PostMapping("/v1/user")
  public Result login3(@RequestBody User user){
    return Result.succResult(200,"ok",user);
  }
 
  @PutMapping("/v1/user")
  public Result putUser(@RequestBody User user){
     return Result.succResult(200,user);
  }
 
  @DeleteMapping("/v1/user/{id}")
  public Result delete(@PathVariable Integer id){
    return Result.succResult(200,id);
  }

Front-end requests need to be configured in main. js

import Axios from 'axios' Vue.prototype.$axios = Axios

The front-end request mode is as follows

The request is made in the following way at the time of call


   this.$axios.get('/api/v1/user/'+this.username+'/'+this.password)
        .then(data=> {
          alert('get//'+data.data.code);
        }).catch(error=> {
         alert(error);
        });
 
      this.$axios.get('/api/v1/user',{
        params: {
          username: this.username,
          password: this.password
        }
      }).then(data =>{
        alert('get'+data.data.data)
      }).catch(error => {
        alert(error)
      });
 
      this.$axios.put('/api/v1/user',{
        id: 1,
        username: this.username,
        password: this.password
      }).then(data => {
        alert(' Data password:'+data.data.data.password)
        alert(' Data username:'+data.data.data.username)
      }).catch(error => {
        alert(error)
      });
 
      this.$axios.delete('/api/v1/user/1')
        .then(data=> {
          alert('delete//'+data.data.code);
        }).catch(error=> {
         alert(error);
        });
        
      this.$axios.post('/api/v1/user',{
        username: this.username,
        password: this.password
      }).then(data => { 
        alert('post'+data.data.data.password)
      }).catch(error => {
        alert(error);
      });
 

Supplementary knowledge: vue combines axios to encapsulate form, restful, get and post

axios Features

1. Create XMLHttpRequests from a browser

2. Create an http request from node. js

3. Support Promise API

4. Intercept requests and responses (that is, interceptor)

5. Transform request data and response data

Step 6 Cancel the request

7. Automatically convert JSON data

8. Client support defenses against XSRF

Installation


npm i axios In fact, in fact, the save
npm i qs --save
npm i element-ui --save
npm i lodash --save

Introduce

1. Introduce the required plug-in into the entry file

main.js


import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import url from './apiUrl'
import api from './apiUtil'

Vue.prototype.$axios = api.generateApiMap(url);
Vue.config.productionTip = false

Vue.use(ElementUI);
new Vue({
 router,
 store,
 render: h => h(App)
}).$mount('#app')

2. Create a new util folder (just store the tool class)

Build two files apiUtil. js and apiUrl. js in util

apiUtil. js encapsulated request body


import axios from 'axios'
import _ from 'lodash'
import router from '@/util/baseRouter.js'
import { Message } from 'element-ui'
import qs from 'qs'

const generateApiMap = (map) => {
 let facade = {}
 _.forEach(map, function (value, key) {
  facade[key] = toMethod(value)
 })
 return facade
}

// Integrated configuration 
const toMethod = (options) => {
 options.method = options.method || 'post'
 return (params, config = {}) => {
  return sendApiInstance(options.method, options.url, params, config)
 }
}

//  Create axios Instances 
const createApiInstance = (config = {}) => {
 const _config = {
  withCredentials: false, //  Cross-domain whether 
  baseURL: '',
  validateStatus: function (status) {
   if(status != 200){
    Message(status+' Background service exception ')
   }
   return status;
  }
 }
 config = _.merge(_config, config)
 return axios.create(config)
}

// Remove spaces before and after entering parameters 
const trim = (param) =>{
 for(let a in param){
  if(typeof param[a] == "string"){
   param[a] = param[a].trim();
  }else{
   param = trim(param[a])
  }
 }
 return param
}

//restful Path parameter replacement 
const toRest = (url,params) => {
 let paramArr = url.match(/(?<=\{).*?(?=\})/gi)
 paramArr.forEach(el=>{
  url = url.replace('{'+el+'}',params[el])
 })
 return url
}

// Encapsulate the request body 
const sendApiInstance = (method, url, params, config = {}) => {
 params = trim(params)
 if(!url){
  return
 }
 let instance = createApiInstance(config)
 // Response interception 
 instance.interceptors.response.use(response => {
   let data = response.data // Server returns data 
   let code = data.meta.respcode // Return information status code 
   let message = data.meta.respdesc // Return information description 
   if(data === undefined || typeof data != "object"){
    Message(' Background corresponding service exception ');
    return false;
   }else if(code != 0){
    Message(message);
    return false;
   }else{
    return data.data;
   }
  },
  error => {
   return Promise.reject(error).catch(res => {
    console.log(res)
   })
  }
 )
 // Request mode judgment 
 let _method = '';
 let _params = {}
 let _url = ''
 if(method === 'form'){
  _method = 'post'
  config.headers = {'Content-Type':'application/x-www-form-urlencoded'}
  _params = qs.stringify(params)
  _url = url
 }else if(method === 'resetful'){
  _method = 'get'
  _params = {}
  _url = toRest(url,params)
 }else if(method === 'get'){
  _method = 'get'
  _params = {
   params: params
  }
  _url = url
 }else if(method === 'post'){
  _method = 'post'
  _params = params
  _url = url
 }else{
  Message(' Request mode does not exist ')
 }
 return instance[_method](_url, _params, config)

}

export default {
 generateApiMap : generateApiMap
}

apiUrl. js Configure all request path parameters

Where the request field in the path of the resetful style request must be written in '{}'


const host= '/api' // Reverse proxy 
export default {
 userAdd:{ url: host + "/user/add", method:"post" },
 userList:{ url: host + "/user/userList", method:"get" },
 userInfo:{ url: host + "/user/userInfo/{id}/{name}", method:"resetful"},
 userInsert:{ url: host + "/login", method:"form"},
}

Use

The input system 1 of the four request modes is passed in the form of object

APP.vue


<template>
 <div class="login">
    <el-button type="primary" @click="submitForm" class="submit_btn"> Login </el-button>
 </div>
</template>
<script>
export default {
 data() {
  return {
  };
 },
 methods:{
  submitForm(){
   this.$axios.userAdd({
    id:'123',
    name:'liyang'
   }).then(data=>{
    console.log(data)
   })
  }
 }
};
</script>

ps: You can also request encapsulation in interceptors. request


Related articles: