vue 調(diào)用 RESTful風(fēng)格接口操作
首先是簡(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.$set 失效的坑 問題發(fā)現(xiàn)及解決方案
這篇文章主要介紹了Vue.$set 失效的坑 問題發(fā)現(xiàn)及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Vue之beforeEach非登錄不能訪問的實(shí)現(xiàn)(代碼親測(cè))
這篇文章主要介紹了Vue之beforeEach非登錄不能訪問的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Vue動(dòng)態(tài)修改網(wǎng)頁標(biāo)題的方法及遇到問題
Vue下有很多的方式去修改網(wǎng)頁標(biāo)題,這里總結(jié)下解決此問題的幾種方案:,需要的朋友可以參考下2019-06-06Mint UI組件庫CheckList使用及踩坑總結(jié)
這篇文章主要介紹了Mint UI組件庫CheckList使用及踩坑總結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12