hello i've an application that uses ["x-access-token"] as token in the header, when i try to access the token in the header i keep gettting "no token provided", i use jwt for authentication
error i get in my console https://imagizer.imageshack.com/img924/4851/2uF6qj.jpg
this is how i'm accessing it in the script tag
<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>
this is my auth middleware for verifying tokens in the browser, my header uses "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"
});
}
};
and my authenticated route to get the current logged in user
// 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
});
}
});
when i check my local storage i see the token https://imagizer.imageshack.com/img923/6844/3MVokP.jpg but can't seem to understand why i keep getting no token provided when trying to get the user in my front end
CodePudding user response:
try
const token = localStorage.getItem("token")
axios
.get("http://localhost:5000/api/auth/user", {
headers: {
Authorization:'Bearer ' token,
'x-access-token': token
}
})