🔍问题:清除服务端接口cookie 获取cookie nuxt添加cookie nuxt的middleware添加cookie
值得参考的文:https://blog.csdn.net/Py1807A/article/details/105380224
https://www.jianshu.com/p/d16919f01288
https://www.jianshu.com/p/95fbd8d7d2fe
nuxt.config.js
router: {
middleware: 'axiosMiddle', //增加header 服务端接口请求的cookie携带
},
axiosMiddle.js
import axios from 'axios'
export default function({req,res}) {
let isClient = process.client;
let isServer = process.server;
console.log("%c 在服务端 发送接口请求","background:red",isServer,"isClient",isClient);
// 在服务端
if (isServer) {
axios.defaults.timeout = 60000;
axios.defaults.contentType = "application/json;charset=utf-8";
axios.defaults.dataType = "text";
axios.defaults.withCredentials = true;
// 获取服务端cookie
console.log("%c 在服务端 发送接口请求","background:red",req.headers.cookie);
if (req.headers !== undefined) {
axios.defaults.headers.Cookie = req.headers.cookie
// axios.defaults.headers.Cookie = {}
// axios.defaults.headers.post['Cookie'] = {};
}
return ;
}
// 在客户端
if (isClient) {
// axios.defaults.headers['Content-Type'] = "application/json";
// axios.defaults.headers['client'] = "pc_web";
// axios.defaults.timeout = 60000;
// axios.defaults.contentType = "application/json;charset=utf-8";
// axios.defaults.dataType = "text";
// headers: {
// "Content-Type": "application/json",
// "client": "pc_web"
// },
console.log("%c 在客户端","background:red",axios.defaults);
// if (req.headers !== undefined) {
// axios.defaults.headers.Cookie = req.headers.cookie
// // axios.defaults.headers.post['Cookie'] = req.headers.cookie;
// }
return ;
}
}
plugins/axios.js
import axios from 'axios';
import apiConfig from "./api.js";
import Vue from 'vue'
let vue = new Vue();
export default ({ app, redirect }, inject) => {
axios.defaults.baseURL = "/api";
let isClient = process.client;
let isServer = process.server;
let service = axios.create();
if(isClient) {
service = axios.create({
timeout: 60000,
headers: {
"Content-Type": "application/json",
"client": "pc_web"
},
contentType: "application/json;charset=utf-8",
dataType: "text",
});
}
// request 请求拦截器
service.interceptors.request.use(
config => {
return config;
},
error => {
Promise.reject(error)
}
)
// response 响应拦截器
service.interceptors.response.use(
result => {
// console.log("this.$fetch response data",result);
const { config, data } = result;
// if (loading != null) loading.close();/
try {
if (result == "") return;
if(config.asyncType == 'async') { // 若是异步的话 就不进行状态的判断 否则需要根据code的状态码判断执行操作
console.log("是异步回调 不需要根据code判断状态码");
}else {
if (data.code == "-95" || data.code == "3") {
return Promise.reject({ code: -1, message: "登录超时" })
}
}
try {
return data;
} catch (e) {
console.error(config.url + "\r\nrequestBody:" + data + "\r\nresponseBody:" + result);
console.error(e);
return Promise.reject({ code: -1, message: "登录超时" })
}
} catch (e) {
vue.$message.warning("解析数据错误");
console.error(config.url + "\r\n" + data);
console.error(e);
}
},
error => {
vue.$message.warning('服务器异常,请联系管理员');
return Promise.reject(error.response) // 返回接口返回的错误信息
}
)
function appendUrlParams(url = '', params = {}) {
let str = String(url).trim();
if (Object.keys(params).length === 0) return str;
if (String(str).indexOf('?') === -1) str += '?';
else str += '&';
for (let key in params) {
str += `${key}=${params[key]}&`;
}
str = String(str).substr(0, str.length - 1);
return str;
}
const $fetch = async (apiName, params = {}, myloading, asyncType, config) => {
let apiNameArr = apiName.split('.');
let apiConfigObj = apiConfig[apiNameArr[0]][apiNameArr[1]][apiNameArr[2]];
if (typeof apiConfigObj !== "object") {
throw new Error("调用api函数函数错误,请检查函数名称是否错误" + apiName);
}
let newConfig = JSON.parse(JSON.stringify(apiConfigObj));
newConfig.asyncType = asyncType;
newConfig.myloading= myloading;
newConfig.data = params;
if (newConfig.method == 'get') { // get请求的话 往url追加参数
if (params) {
newConfig.url = appendUrlParams(newConfig.url, params)
}
}
if (myloading == 'hide') { // 若是传的是null的话 则表示不需要loading动效
newConfig.myloading= myloading;
console.log("myloading 隐藏");
} else {
// 需要引入全局变量 zyd_loading
newConfig.myloading= '1111';
// var loading = zyd_loading.myLoading();
console.log("myloading 显示动效");
}
return service(newConfig);
}
app.fetch = $fetch // 名称
let install = {
install(Vue) {
Vue.prototype.$fetch = $fetch
}
}
Vue.use(install)
};
三:一个最基础的登录页面
<template>
<section class="">
</section>
</template>
<script>
export default {
name: '',
components: {},
data() {
return {}
},
async asyncData( {app, route, store} ) {
let fetchLogin = await app.fetch('loginApi.login.loginInfo', {},'','async').then(r=>{
if(Object.keys(r.data).length){
store.dispatch("setuserInfo", r.data)
store.dispatch("setloginState", true)
}else{
store.dispatch("setloginState", false)
}
return r.data;
}).catch(err => console.log(err))
if(store.state.loginState) {
console.log("asyncData 已经登录",store.state.userInfo);
}else {
console.log("asyncData 未登录");
}
},
mounted() {
this.init();
//this.jj();
},
methods: {
init() {
},
async jj() {
let fetchLogin = await this.$fetch('loginApi.login.loginInfo', {},'k','async').then(r=>{
if(Object.keys(r.data).length){
store.dispatch("setuserInfo", r.data)
store.dispatch("setloginState", true)
}else{
store.dispatch("setloginState", false)
}
return r.data;
}).catch(err => console.log('err',err))
console.log("methodsjh jjj hjjjhhhh jjjfetchLogin",fetchLogin);
},
}
}
</script>
<style scoped lang="scss">
</style>