1、前端请求头带token
import axios from 'axios'
import Vue from 'vue'
import router from './router'
const http = axios.create({
//baseURL:process.env.VUE_APP_API_URL || '/admin/api',
baseURL:"http://localhost:3000/admin/api"
})
//token不止一种类型,Bearer为行业规范,后面需要带一个空格
//给请求头带token过去
http.interceptors.request.use(function(config){
if(localStorage.token){
config.headers.Authorization = 'Bearer '+localStorage.token || ''
}
return config;
},function(error){
return Promise.reject(error)
})
2、后端接口校验
const jwt = require("jsonwebtoken");
const AdminUser = require("../models/AdminUser");
//authorization后端需首字母小写,前端首字母为大写
//split(' ') 注意要有空格才能分割正确的token
router.get('/',async (req,res,next)=>{
const token = String(req.headers.authorization || ' ').split(' ').pop();
const {id} = jwt.verify(token,app.get('secret'));
//req.user让后面每个接口都能获取到
//通过token获取到的id去模型里面找对应的数据
req.user = await AdminUser.findById(id);
})