这里单独写了一个js文件封装登录的接口,因为密码登录的Content-Type不是application/json而是application/x-www=-form-urlencoded
所以我的登录请求的接口是单独引入方法的
直接上代码吧
(需要下载qs的插件别忘了,省的自己拼接)
login.js
import axios from 'axios'
import qs from 'qs'
var http = axios.create({
baseURL: process.env.VUE_APP_BASEURL,
timeout: 5000
});
axios.defaults.headers.post['Content-Type'] = 'application/x-www=-form-urlencoded'
http.param = (data = {}, contentType = 'application/x-www-form-urlencoded') => {
return contentType === 'application/x-www-form-urlencoded' ? qs.stringify(data) : (contentType === 'application/json' ? JSON.stringify(data) : data);
}
//http拦截器
http.interceptors.request.use(config => {
config.headers['Authorization'] = 'Basic c2VydmljZS1yZXNvdXJjZTpqc3huaXUtcmVzb3VyY2U=';
return config;
}), error => {
console.log(error)
}
// //登录的接口,是客户端id和客户端密码,这两个值是唯一确定的,后台给的
// export function httpLoginPost(url,param={}){
// return new Promise((resolve,reject)=>{
// http.post(url,http.param(param),{auth:{
// username: 'admin',
// password: '123456'
// }})
// .then(response=>{
// resolve(response.data)
// })
// .catch(err=>{
// reject(err)
// })
// })
// }
//登录的接口
export function httpLoginPost(url, param = {}) {
return new Promise((resolve, reject) => {
http.post(url, http.param(param))
.then(response => {
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
}
在登录的vue页面写法
import { httpLoginPost } from "@/axios/login.js";
methods: {
//登录
onSubmit() {
this.$refs.ruleForm.validate((valid) => {
if (valid) {
//登录请求
httpLoginPost("/auth/oauth/token", {
username: this.form.username, //username和password是输入框输入的值
password: this.form.password,
grant_type: "password", //grant_type表示授权类型,固定为"password",必选项
})
.then((res) => {
console.log(res);
if (res.code === 200) {
// this.$ls.set("token", res.data.access_token);
// this.$api.getNavList().then((res) => {
// if (res.code === 200) {
// this.$ls.set(
// "navList",
// this.handleTree(res.data, "id", "pid"),
// 60 * 60 * 1000 * 24
// );
// } else {
// // console.log(res);
// this.$message.error(res.msg);
// }
// });
//路由跳转
this.$message.success("登录成功");
this.$router.push("/index");
if (this.checkAgree) {
this.setCookie("username", this.form.username, 7);
this.setCookie("password", this.form.password, 7);
} else {
this.setCookie("username", "");
this.setCookie("password", "");
}
} else {
this.$message.error(res.msg);
}
})
.catch((error) => {
console.log(error);
});
}
});
},
// 获取cookie
getCookie(key) {
if (document.cookie.length > 0) {
var start = document.cookie.indexOf(key + "=");
if (start !== -1) {
start = start + key.length + 1;
var end = document.cookie.indexOf(";", start);
if (end === -1) end = document.cookie.length;
return unescape(document.cookie.substring(start, end));
}
}
return "";
},
// 保存cookie
setCookie(cName, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie =
cName +
"=" +
decodeURIComponent(value) +
(expiredays == null ? "" : ";expires=" + exdate.toGMTString());
},
},