SoFunction
Updated on 2025-04-07

vue calls RESTful style interface operation

First of all, the simple java interface code

I wrote four interfaces to make 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 (200,username+"--"+password);
  }
 
  @PostMapping("/v1/user")
  public Result login3(@RequestBody User user){
    return (200,"ok",user);
  }
 
  @PutMapping("/v1/user")
  public Result putUser(@RequestBody User user){
     return (200,user);
  }
 
  @DeleteMapping("/v1/user/{id}")
  public Result delete(@PathVariable Integer id){
    return (200,id);
  }

Front-end requests need to be configured in

import Axios from 'axios' .$axios = Axios

The front-end request method is as follows

When calling, make the request in the following way

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

Supplementary knowledge:Vue combines axios package form, restful, get, and post four styles requests:

Features of axios

1. Create XMLHttpRequests from the browser

2. Create http request from

3. Support Promise API

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

5. Convert request data and response data

6. Cancel the request

7. Automatically convert JSON data

8. Client supports defense XSRF

Install

npm i axios–save
npm i qs --save
npm i element-ui --save
npm i lodash --save

Introduced

1. Introduce the required plugins in the entry file

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

.$axios = (url);
 = false

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

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

Build in util, two files

Encapsulation request body

import axios from 'axios'
import _ from 'lodash'
import router from '@/util/'
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 configurationconst toMethod = (options) => {
  =  || 'post'
 return (params, config = {}) => {
  return sendApiInstance(, , params, config)
 }
}

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

//Remove spaces before and after entering parametersconst 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 replacementconst toRest = (url,params) => {
 let paramArr = (/(?<=\{).*?(?=\})/gi)
 (el=>{
  url = ('{'+el+'}',params[el])
 })
 return url
}

//Encapsulation request bodyconst sendApiInstance = (method, url, params, config = {}) => {
 params = trim(params)
 if(!url){
  return
 }
 let instance = createApiInstance(config)
 //Response to intercept (response => {
   let data =  //The server returns data   let code =  //Return information status code   let message =  //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 ;
   }
  },
  error => {
   return (error).catch(res => {
    (res)
   })
  }
 )
 //Judgement of request method let _method = '';
 let _params = {}
 let _url = ''
 if(method === 'form'){
  _method = 'post'
   = {'Content-Type':'application/x-www-form-urlencoded'}
  _params = (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('The request method does not exist')
 }
 return instance[_method](_url, _params, config)

}

export default {
 generateApiMap : generateApiMap
}

Configure all request path parameters

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

const host= '/api' //Reverse proxyexport 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 entry parameters of the four request methods are uniformly transmitted in the form of an object.

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

ps: You can also encapsulate it in requests

The above vue call RESTful style interface operation is all the content I share with you. I hope you can give you a reference and I hope you support me more.