我有一个应用程序使用["x-access-token"]
作为标头中的令牌,当我尝试访问标头中的令牌时,我一直得到“未提供令牌”。我使用jwt进行身份验证
这就是我在script
标签中访问它的方式:
<script>
import axios from "axios";
export default {
data() {
return {
name: "",
email: "",
};
},
created() {
//user is not authorized
if (localStorage.getItem("token") === null) {
this.$router.push("/login");
}
},
mounted() {
axios
.get("http://localhost:5000/api/auth/user", {
headers: {
Authorization:'Bearer' + token,
token: localStorage.getItem("token") }
})
.then(res => {
console.log(res)
this.name = res.data.foundUser.name;
this.email = res.data.foundUser.email;
});
},
};
</script>
这是我的授权中间件,用于验证浏览器中的令牌,我的标头使用“x-access-token”
const jwt = require("jsonwebtoken");
module.exports = function (req, res, next) {
let token = req.headers["x-access-token"] || req.headers["authorization"];
let checkBearer = "Bearer ";
if (token) {
if (token.startsWith(checkBearer)) {
token = token.slice(checkBearer.length, token.length);
}
jwt.verify(token, process.env.SECRET, (err, decoded) => {
if (err) {
res.json({
success: false,
message: "Failed to authenticate"
});
} else {
req.decoded = decoded;
next();
}
});
} else {
res.json({
success: false,
message: "No token Provided"
});
}
};
和我的已验证路由来获取当前登录用户
// Get Profile
router.get("/auth/user", verifyToken, async (req, res) => {
try {
let foundUser = await User.findOne({
_id: req.decoded._id
}).populate(
"address"
);
if (foundUser) {
res.json({
success: true,
user: foundUser
});
}
} catch (err) {
res.status(500).json({
success: false,
message: err.message
});
}
});
当我检查本地存储时,我看到了令牌,但似乎无法理解为什么我在尝试获取前端用户时一直没有获得令牌
1条答案
按热度按时间vjhs03f71#
尝试