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?savenpm i qs --savenpm i element-ui --savenpm 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 = falseVue.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)⑶昂笕タ崭馽onst 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è)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器2. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理3. phpstudy apache開啟ssi使用詳解4. ASP.NET MVC使用異步Action的方法5. 爬取今日頭條Ajax請(qǐng)求6. jsp文件下載功能實(shí)現(xiàn)代碼7. ajax實(shí)現(xiàn)頁(yè)面的局部加載8. AJAX的跨域問題解決方案9. uni-app結(jié)合.NET 7實(shí)現(xiàn)微信小程序訂閱消息推送10. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算
