后端使用nodejs,mysql,express,登录功能实现:
// 1.登录的处理函数
exports.login = (req, res) => {
console.log(req.body);
const userInfo=req.body
const sql=`select * from t_admin where admin_name=?`
db.query(sql,userInfo.admin_name,function(err,results){
if(err) {return res.cc(err)}
if(results.length!==1) return res.cc('登录失败')
// 调用 bcrypt.compareSync(用户提交的密码, 数据库中的密码) 方法比较密码是否一致
const compareResult = bcrypt.compareSync(userInfo.admin_pwd, results[0].admin_pwd)
// 如果对比的结果等于 false, 则证明用户输入的密码错误
if (!compareResult) {
return res.cc('登录失败!')
}
// 登陆成功,生成token
const user = {...results[0],admin_pwd:''};
// 生成token
const tokenStr = jwt.sign(user,config.jwtSecretKey,{
expiresIn:'10h'
})
res.send({
status: 200,
message: '登录成功!',
// 为了方便客户端使用 Token,在服务器端直接拼接上 Bearer 的前缀
token: 'Bearer ' + tokenStr,
})
})
}
通过postman测试接口可以正常实现功能,但是在前端,浏览器会报错,在确定账号密码正确的情况下,说我输入用户名必须是长度在1~10之间的字符串,后发现后端的数据格式是application/x-www-form-urlencoded,而浏览器默认post发送的是json格式数据,所以发生了登录错误。
解决方法:
在前端添加请求拦截器,其中request是axios实例对象
request.interceptors.request.use(
config => {
if (config.method === 'post') {
let data = ''
for (const item in config.data) {
if (config.data[item]!==null) {
data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'
}
}
config.data = data.slice(0, data.length - 1)
}
return config
}, error => {
console.log('在request拦截器显示错误', error.response)
return Promise.reject(error)
}
)