vue是如何调用RESTful风格接口的(axios)

Posted 石工记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue是如何调用RESTful风格接口的(axios)相关的知识,希望对你有一定的参考价值。

首先是简单的java接口代码

写了四个让前端请求的接口,以下为代码

  @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);
  

前端请求需要在main.js中配置

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

前端请求方式如下

在调用的时候用以下方式进行请求

   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('数据password:'+data.data.data.password)
        alert('数据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);
      ); 

补充知识:vue结合axios封装form,restful,get,post四种风格请求

axios特点

1.从浏览器中创建 XMLHttpRequests

2.从 node.js 创建 http 请求

3.支持 Promise API

4.拦截请求和响应 (就是有interceptor)

5.转换请求数据和响应数据

6.取消请求

7.自动转换 JSON 数据

8.客户端支持防御 XSRF

安装

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

引入

1.在入口文件中引入所需插件

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.新建一个util文件夹(只要存放工具类)

在util中建apiUtil.js , apiUrl.js两个文件

apiUtil.js 封装请求体

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


//整合配置
const toMethod = (options) => 
 options.method = options.method || 'post'
 return (params, config = ) => 
  return sendApiInstance(options.method, options.url, params, config)
 


// 创建axios实例
const createApiInstance = (config = ) => 
 const _config = 
  withCredentials: false, // 跨域是否
  baseURL: '',
  validateStatus: function (status) 
   if(status != 200)
    Message(status+':后台服务异常')
   
   return status;
  
 
 config = _.merge(_config, config)
 return axios.create(config)


//入参前后去空格
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路径参数替换
const toRest = (url,params) => 
 let paramArr = url.match(/(&#63;<=\\).*&#63;(&#63;=\\)/gi)
 paramArr.forEach(el=>
  url = url.replace(''+el+'',params[el])
 )
 return url


//封装请求体
const sendApiInstance = (method, url, params, config = ) => 
 params = trim(params)
 if(!url)
  return
 
 let instance = createApiInstance(config)
 //响应拦截
 instance.interceptors.response.use(response => 
   let data = response.data //服务端返回数据
   let code = data.meta.respcode //返回信息状态码
   let message = data.meta.respdesc //返回信息描述
   if(data === undefined || typeof data != "object")
    Message('后台对应服务异常');
    return false;
   else if(code != 0)
    Message(message);
    return false;
   else
    return data.data;
   
  ,
  error => 
   return Promise.reject(error).catch(res => 
    console.log(res)
   )
  
 )
 //请求方式判断
 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('请求方式不存在')
 
 return instance[_method](_url, _params, config)



export default 
 generateApiMap : generateApiMap

apiUrl.js 配置所有请求路径参数

其中resetful风格请求的路径中的请求字段必须写在 ‘'中

const host= '/api' //反向代理
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",

使用

四种请求方式的入参统一都以object形式传入

APP.vue

<template>
 <div class="login">
    <el-button type="primary" @click="submitForm" class="submit_btn">登录</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:入参也可以再请求interceptors.request中封装

以上是关于vue是如何调用RESTful风格接口的(axios)的主要内容,如果未能解决你的问题,请参考以下文章

Vue 使用typescript, 优雅的调用swagger API

Restful风格wcf调用4——权限认证

Axios学习

Axios学习

Axios学习

Restful风格wcf调用3——Stream