电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

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

瀏覽:99日期:2022-12-10 08:27:54

首先是簡(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)。

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 土壤肥料养分速测仪_测土配方施肥仪_土壤养分检测仪-杭州鸣辉科技有限公司 | 河南膏药贴牌-膏药代加工-膏药oem厂家-洛阳今世康医药科技有限公司 | 断桥铝破碎机_发动机破碎机_杂铝破碎机厂家价格-皓星机械 | 蒸汽热收缩机_蒸汽发生器_塑封机_包膜机_封切收缩机_热收缩包装机_真空机_全自动打包机_捆扎机_封箱机-东莞市中堡智能科技有限公司 | 首页_中夏易经起名网| 首页-恒温恒湿试验箱_恒温恒湿箱_高低温试验箱_高低温交变湿热试验箱_苏州正合 | 对照品_中药对照品_标准品_对照药材_「格利普」高纯中药标准品厂家-成都格利普生物科技有限公司 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库 | 流变仪-热分析联用仪-热膨胀仪厂家-耐驰科学仪器商贸 | 一航网络-软件测评官网 | 代做标书-代写标书-专业标书文件编辑-「深圳卓越创兴公司」 | 焊锡丝|焊锡条|无铅锡条|无铅锡丝|无铅焊锡线|低温锡膏-深圳市川崎锡业科技有限公司 | 气体检测仪-氢气检测仪-可燃气体传感器-恶臭电子鼻-深国安电子 | 电位器_轻触开关_USB连接器_广东精密龙电子科技有限公司 | 安徽净化板_合肥岩棉板厂家_玻镁板厂家_安徽科艺美洁净科技有限公司 | 潜水搅拌机-双曲面搅拌机-潜水推进器|奥伯尔环保 | 斗式提升机,斗式提升机厂家-淄博宏建机械有限公司 | 打造全球沸石生态圈 - 国投盛世| 北京普辉律师事务所官网_北京律师24小时免费咨询|法律咨询 | 特种阀门-调节阀门-高温熔盐阀-镍合金截止阀-钛阀门-高温阀门-高性能蝶阀-蒙乃尔合金阀门-福建捷斯特阀门制造有限公司 | ◆大型吹塑加工|吹塑加工|吹塑代加工|吹塑加工厂|吹塑设备|滚塑加工|滚塑代加工-莱力奇塑业有限公司 | 复合土工膜厂家|hdpe防渗土工膜|复合防渗土工布|玻璃纤维|双向塑料土工格栅-安徽路建新材料有限公司 | 珠海白蚁防治_珠海灭鼠_珠海杀虫灭鼠_珠海灭蟑螂_珠海酒店消杀_珠海工厂杀虫灭鼠_立净虫控防治服务有限公司 | 自清洗过滤器-全自动自清洗过反冲洗过滤器 - 中乂(北京)科技有限公司 | 培训中心-海南香蕉蛋糕加盟店技术翰香原中心官网总部 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 | 湖南自考_湖南自学考试| 一体化隔油提升设备-餐饮油水分离器-餐厨垃圾处理设备-隔油池-盐城金球环保产业发展有限公司 | 首页 - 军军小站|张军博客 | 三氯异氰尿酸-二氯-三氯-二氯异氰尿酸钠-优氯净-强氯精-消毒片-济南中北_优氯净厂家 | 焊接烟尘净化器__焊烟除尘设备_打磨工作台_喷漆废气治理设备 -催化燃烧设备 _天津路博蓝天环保科技有限公司 | 高速龙门架厂家_监控杆_多功能灯杆_信号灯杆_锂电池太阳能路灯-鑫世源照明 | 中国产业发展研究网 - 提供行业研究报告 可行性研究报告 投资咨询 市场调研服务 | 塑胶跑道施工-硅pu篮球场施工-塑胶网球场建造-丙烯酸球场材料厂家-奥茵 | 京马网,京马建站,网站定制,营销型网站建设,东莞建站,东莞网站建设-首页-京马网 | 重庆网站建设,重庆网站设计,重庆网站制作,重庆seo,重庆做网站,重庆seo,重庆公众号运营,重庆小程序开发 | 北京发电车出租-发电机租赁公司-柴油发电机厂家 - 北京明旺盛安机电设备有限公司 | 高压油管,液压接头,液压附件-烟台市正诚液压附件 | 交通气象站_能见度检测仪_路面状况监测站- 天合环境科技 | 深圳高新投三江工业消防解决方案提供厂家_服务商_园区智慧消防_储能消防解决方案服务商_高新投三江 | 全温度恒温培养摇床-大容量-立式-远红外二氧化碳培养箱|南荣百科 | 质检报告_CE认证_FCC认证_SRRC认证_PSE认证_第三方检测机构-深圳市环测威检测技术有限公司 |