vue 调用 RESTful风格接口操作
程序员文章站
2022-12-05 20:01:35
首先是简单的java接口代码写了四个让前端请求的接口,以下为代码 @getmapping("/v1/user/{username}/{password}") public result login...
首先是简单的java接口代码
写了四个让前端请求的接口,以下为代码
@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); }
前端请求需要在main.js中配置
import axios from 'axios' vue.prototype.$axios = axios
前端请求方式如下
在调用的时候用以下方式进行请求
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('数据password:'+data.data.data.password) alert('数据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); });
补充知识:vue结合axios封装form,restful,get,post四种风格请求
axios特点
1.从浏览器中创建 xmlhttprequests
2.从 node.js 创建 http 请求
3.支持 promise api
4.拦截请求和响应 (就是有interceptor)
5.转换请求数据和响应数据
6.取消请求
7.自动转换 json 数据
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.新建一个util文件夹(只要存放工具类)
在util中建apiutil.js , apiurl.js两个文件
apiutil.js 封装请求体
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) } } // 创建axios实例 const createapiinstance = (config = {}) => { const _config = { withcredentials: false, // 跨域是否 baseurl: '', validatestatus: function (status) { if(status != 200){ message(status+':后台服务异常') } return status; } } config = _.merge(_config, config) return axios.create(config) } //入参前后去空格 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路径参数替换 const torest = (url,params) => { let paramarr = url.match(/(?<=\{).*?(?=\})/gi) paramarr.foreach(el=>{ url = url.replace('{'+el+'}',params[el]) }) return url } //封装请求体 const sendapiinstance = (method, url, params, config = {}) => { params = trim(params) if(!url){ return } let instance = createapiinstance(config) //响应拦截 instance.interceptors.response.use(response => { let data = response.data //服务端返回数据 let code = data.meta.respcode //返回信息状态码 let message = data.meta.respdesc //返回信息描述 if(data === undefined || typeof data != "object"){ message('后台对应服务异常'); return false; }else if(code != 0){ message(message); return false; }else{ return data.data; } }, error => { return promise.reject(error).catch(res => { console.log(res) }) } ) //请求方式判断 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('请求方式不存在') } return instance[_method](_url, _params, config) } export default { generateapimap : generateapimap }
apiurl.js 配置所有请求路径参数
其中resetful风格请求的路径中的请求字段必须写在 ‘{}'中
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"}, }
使用
四种请求方式的入参统一都以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:入参也可以再请求interceptors.request中封装
以上这篇vue 调用 restful风格接口操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。