【发布时间】:2019-06-13 03:39:10
【问题描述】:
我对网络开发还是很陌生,所以如果解决方案很明显或者我的问题被问得不好,我提前道歉。
所以:我想使用 JWT 来验证我的用户。我使用 axios、vue.js,当然还有 JWT。我想访问安全路线:
router.post('/secureroute', checkAuth, (req, res) => {
res.status(200).json({
message: 'all ok'
})
});
为了做到这一点,我使用了这个check-auth.js:
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
console.log(token);
const decoded = jwt.verify(token, process.env.SECRET_KEY);
next();
} catch (error) {
return res.status(401).json({
message: 'Auth failed'
})
}
next();
}
我的 Login.vue 的一部分:
methods: {
login() {
if (!this.username) this.alertUsername = true;
if (!this.password) this.alertPassword = true;
axios
.post("/user/login", {
username: this.username,
password: this.password
})
.then(res => {
localStorage.setItem("usertoken", res.data.token);
if (res.data.token) {
console.log("Success");
router.push({ name: "start" });
} else {
this.alertWrong = true;
}
this.username = "";
this.password = "";
})
.catch(err => {
console.log(err);
});
this.emitMethod();
}
使用带有授权标头的邮递员,一切似乎都正常。但是经过几个小时的互联网搜索和尝试,我根本不知道如何让它与真实的网站一起使用。我想将 JWT 作为授权标头传递。我知道使用 axios 是可能的,但我真的不知道在我的示例中如何做到这一点。
【问题讨论】:
标签: javascript vue.js authorization jwt axios