最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue 調(diào)用 RESTful風(fēng)格接口操作

 更新時(shí)間:2020年08月11日 15:00:47   作者:BeniLiy  
這篇文章主要介紹了vue 調(diào)用 RESTful風(fēng)格接口操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

首先是簡(jiǎn)單的java接口代碼

寫(xiě)了四個(gè)讓前端請(qǐng)求的接口,以下為代碼

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

前端請(qǐng)求需要在main.js中配置

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

前端請(qǐng)求方式如下

在調(diào)用的時(shí)候用以下方式進(jìn)行請(qǐng)求

   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('數(shù)據(jù)password:'+data.data.data.password)
        alert('數(shù)據(jù)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);
      });
 

補(bǔ)充知識(shí):vue結(jié)合axios封裝form,restful,get,post四種風(fēng)格請(qǐng)求

axios特點(diǎn)

1.從瀏覽器中創(chuàng)建 XMLHttpRequests

2.從 node.js 創(chuàng)建 http 請(qǐng)求

3.支持 Promise API

4.攔截請(qǐng)求和響應(yīng) (就是有interceptor)

5.轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)

6.取消請(qǐng)求

7.自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)

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.新建一個(gè)util文件夾(只要存放工具類)

在util中建apiUtil.js , apiUrl.js兩個(gè)文件

apiUtil.js 封裝請(qǐng)求體

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)
 }
}

// 創(chuàng)建axios實(shí)例
const createApiInstance = (config = {}) => {
 const _config = {
  withCredentials: false, // 跨域是否
  baseURL: '',
  validateStatus: function (status) {
   if(status != 200){
    Message(status+':后臺(tái)服務(wù)異常')
   }
   return status;
  }
 }
 config = _.merge(_config, config)
 return axios.create(config)
}

//入?yún)⑶昂笕タ崭?
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路徑參數(shù)替換
const toRest = (url,params) => {
 let paramArr = url.match(/(?<=\{).*?(?=\})/gi)
 paramArr.forEach(el=>{
  url = url.replace('{'+el+'}',params[el])
 })
 return url
}

//封裝請(qǐng)求體
const sendApiInstance = (method, url, params, config = {}) => {
 params = trim(params)
 if(!url){
  return
 }
 let instance = createApiInstance(config)
 //響應(yīng)攔截
 instance.interceptors.response.use(response => {
   let data = response.data //服務(wù)端返回?cái)?shù)據(jù)
   let code = data.meta.respcode //返回信息狀態(tài)碼
   let message = data.meta.respdesc //返回信息描述
   if(data === undefined || typeof data != "object"){
    Message('后臺(tái)對(duì)應(yīng)服務(wù)異常');
    return false;
   }else if(code != 0){
    Message(message);
    return false;
   }else{
    return data.data;
   }
  },
  error => {
   return Promise.reject(error).catch(res => {
    console.log(res)
   })
  }
 )
 //請(qǐng)求方式判斷
 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('請(qǐng)求方式不存在')
 }
 return instance[_method](_url, _params, config)

}

export default {
 generateApiMap : generateApiMap
}

apiUrl.js 配置所有請(qǐng)求路徑參數(shù)

其中resetful風(fēng)格請(qǐng)求的路徑中的請(qǐng)求字段必須寫(xiě)在 ‘{}'中

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"},
}

使用

四種請(qǐng)求方式的入?yún)⒔y(tǒng)一都以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:入?yún)⒁部梢栽僬?qǐng)求interceptors.request中封裝

以上這篇vue 調(diào)用 RESTful風(fēng)格接口操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

临高县| 叶城县| 凤台县| 南郑县| 江川县| 连山| 滨州市| 庄浪县| 沈阳市| 浑源县| 时尚| 城固县| 仁怀市| 桂阳县| 定陶县| 东丽区| 香格里拉县| 青川县| 托克逊县| 大丰市| 威宁| 闽侯县| 麦盖提县| 聂荣县| 淮南市| 乌兰浩特市| 芮城县| 勐海县| 陈巴尔虎旗| 墨玉县| 马龙县| 凉城县| 泌阳县| 砀山县| 台山市| 邯郸市| 开化县| 扶沟县| 贺兰县| 神农架林区| 锡林郭勒盟|