I use an route app.get('/jwtid') to catch the token on home in my react app. This route work with postman and my sever send me the token but when I do a get axios on React I got an undefined token on my server.
Here is my authJwt.js:
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
verifyToken = (req, res, next) => {
const token = req.cookies.jwt;
console.log(req.cookies.jwt);
if (!token) {
return res.status(403).send({
message: "No token provided!"
});
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({
message: "Unauthorized!"
});
}
req.id = decoded.id;
next();
});
};
const authJwt = {
verifyToken: verifyToken,
};
module.exports = authJwt;
My route jwtid:
app.get('/jwtid', verifyToken, (req, res) => {
res.status(200).send(res.locals.id)
});
My React get token app.js React:
import "./App.css";
import React from "react";
import Route from './components/Route';
import axios from "axios";
import { token } from "morgan";
import { EmailJSResponseStatus } from "@emailjs/browser";
function App() {
let user = JSON.parse(localStorage.getItem("user"));
console.log(user);
console.log("tokenId")
const config ={
token: user
};
console.log(config)
console.log("config")
axios({
'method': "get",
'url': `${process.env.REACT_APP_API_URL}jwtid`, config,
'withCredentials': true,
'body': JSON.stringify(config),
}) .then(function (response) {
console.log(response.data);
// I need this data here ^^
return response.data;
})
.then((res) => {
if (res.error) {
console.log(res.error);
alert("The response data is invalid")
} })
.catch((err) => console.log("No token"))
return (
<div>
<Route/>
</div>
);
}
export default App;
And I catch token withe localstorage so I call it on my axios get token, this is my return:
If someone have an solution :')
I found the solution: In my front "login.js" when I call "axios" for post my login, I must add withCredentials: true. Like this:
axios({
method: "post",
url: `${process.env.REACT_APP_API_URL}api/auth/login`,
data: values,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(values),
})
Thank to this post: cookie httponly not sent