欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

寫了四個(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)求字段必須寫在 ‘{}'中

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)文章

  • Vue-component全局注冊(cè)實(shí)例

    Vue-component全局注冊(cè)實(shí)例

    今天小編就為大家分享一篇Vue-component全局注冊(cè)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • Vue手寫dialog組件模態(tài)框過程詳解

    Vue手寫dialog組件模態(tài)框過程詳解

    這篇文章主要介紹了Vue手寫dialog組件模態(tài)框過程,dialog組件為模態(tài)框,因此應(yīng)該是固定定位到頁面上面的,并且需要留一定的插槽來讓使用者自定義顯示內(nèi)容
    2023-02-02
  • Vue.$set 失效的坑 問題發(fā)現(xiàn)及解決方案

    Vue.$set 失效的坑 問題發(fā)現(xiàn)及解決方案

    這篇文章主要介紹了Vue.$set 失效的坑 問題發(fā)現(xiàn)及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Vue之beforeEach非登錄不能訪問的實(shí)現(xiàn)(代碼親測(cè))

    Vue之beforeEach非登錄不能訪問的實(shí)現(xiàn)(代碼親測(cè))

    這篇文章主要介紹了Vue之beforeEach非登錄不能訪問的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Vue2.0 $set()的正確使用詳解

    Vue2.0 $set()的正確使用詳解

    這篇文章主要介紹了Vue2.0 $set()的正確使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • Vue首屏優(yōu)化方案小結(jié)

    Vue首屏優(yōu)化方案小結(jié)

    在Vue項(xiàng)目中,引入到工程中的所有js、css文件,編譯時(shí)都會(huì)被打包進(jìn)vendor.js,瀏覽器在加載該文件之后才能開始顯示首屏,本文主要介紹了Vue首屏優(yōu)化方案小結(jié),感興趣的可以了解一下
    2024-05-05
  • Vue動(dòng)態(tài)修改網(wǎng)頁標(biāo)題的方法及遇到問題

    Vue動(dòng)態(tài)修改網(wǎng)頁標(biāo)題的方法及遇到問題

    Vue下有很多的方式去修改網(wǎng)頁標(biāo)題,這里總結(jié)下解決此問題的幾種方案:,需要的朋友可以參考下
    2019-06-06
  • vue組件三大核心概念圖文詳解

    vue組件三大核心概念圖文詳解

    本文主要介紹屬性、事件和插槽這三個(gè)vue基礎(chǔ)概念、使用方法及其容易被忽略的一些重要細(xì)節(jié),感興趣的朋友跟隨小編一起看看吧
    2019-05-05
  • Mint UI組件庫CheckList使用及踩坑總結(jié)

    Mint UI組件庫CheckList使用及踩坑總結(jié)

    這篇文章主要介紹了Mint UI組件庫CheckList使用及踩坑總結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-12-12
  • Vue?eventBus事件總線封裝后再用的方式

    Vue?eventBus事件總線封裝后再用的方式

    EventBus稱為事件總線,當(dāng)兩個(gè)組件屬于不同的兩個(gè)組件分支,或者兩個(gè)組件沒有任何聯(lián)系的時(shí)候,不想使用Vuex這樣的庫來進(jìn)行數(shù)據(jù)通信,就可以通過事件總線來進(jìn)行通信,這篇文章主要給大家介紹了關(guān)于Vue?eventBus事件總線封裝后再用的相關(guān)資料,需要的朋友可以參考下
    2022-06-06

最新評(píng)論