前言
提示:这里可以添加本文要记录的大概内容:
vue-admin前后端分离管理后台模板二次开发中适配url接口
提示:以下是本篇文章正文内容,下面案例可供参考
一、编写request请求文件
const https = require('https');
// 不需要 body 的请求
const noBodyReqs = ['head','get','copy','purge','unlock'];
// 可能需要 body 的请求
const hasBodyReqs = ['post','put','patch','delete','options','link','unlink','lock','propfind','view'];
const HttpsClient = {};
noBodyReqs.concat(hasBodyReqs).forEach(method => {
HttpsClient[method] = obj => {
return new Promise(function (cb) {
const options = {
host: obj.host,
port: 443,
path: obj.path,
method,
headers: obj.headers ? obj.headers : {},
};
const req = https.request(options, res => {
let chunks = Buffer.from([]);
let chunksLength = chunks.length;
res.on('data', chunk => {
chunks = Buffer.concat([chunks,chunk],chunksLength + chunk.length);
chunksLength = chunks.length;
});
res.on('end', () => {
cb(chunks.toString());
});
});
req.on('error', e => {console.log(`request error: ${e}`);});
if(hasBodyReqs.indexOf(method) !== -1) req.write(obj.body);
req.end();
});
}
});
module.exports = HttpsClient;
二、使用步骤
1.寻找页面请求方法
代码如下(示例):
//该模板大多数情况都是调用store中的方法
this.$store.dispatch('user/login', this.loginForm).then((res) => {
if(res){
this.$router.push({
path: this.redirect || '/'
})
}else{
alert('Login failed, account or password error!');
}
this.loading = false
}).catch(() => {
this.loading = false
})
// user login(store文件中的modules的user模块)
login({ commit }, userInfo) {
const { username, password,type} = userInfo
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password ,type:type}).then(res => {
commit('SET_TOKEN', "admin-token")
setToken("admin-token")
resolve(res)
}).catch(error => {
reject(error)
})
})
//api文件中的user.js文件
const HttpsClient = require('@/utils/HttpsClient');//导入request
export function login(data) {
var ddl = JSON.stringify(data)
return HttpsClient.post({
host: '*******',//接口地址(去掉https://)
path: '/adminget',//接口名称
headers: {
'content-type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*"
},
body: ddl
}).then(res => {
return eval("(" + res + ")");//数据的解码(json格式化)
}).catch((err) => {
return err;
});
}
总结
提示:这里对文章进行总结:
整个模板是用的mock模拟数据返回,需要先了解mock的用法,理清整个方法的调用过程,理一下请求方法的流程。