userAction.js -> Frontend, Action
export const login = (userID, password) => async (dispatch) => {
try {
dispatch({ type: USER_LOGIN_REQUEST });
const url = "http://localhost:8080/authenticate/";
const config = {
auth: {
username: userID,
password,
},
};
const data = {};
const response = await axios.post(
url,
data,
config,
)
dispatch({ type: USER_LOGIN_SUCCESS, payload: config});
if (response.status === 200) {
// Login succeeded
const token = response.data.token;
console.log("TOKEN\n" + token);
config.token = response.data.token;
console.log(response.data.token);
}
localStorage.setItem("userInfo", JSON.stringify(config) );
}
My login function in REST Server :
exports.login = async (req,res) =>{
const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
const [userID, password] = Buffer.from(b64auth, 'base64').toString().split(':');
const user = await User.findOne({ userID: userID });
if(!user) return res.status(400).send('User not found');
const validPass = await bcrypt.compare(password, user.password);
if(!validPass) return res.status(400).send('Incorrect Password');
//const token = generateToken(user.userID);
let payload = {
userID: user.userID
}
const token = generateToken(userID);
res.header('Authorization', 'Bearer ' + token).json(token);
console.log(user);
return res.json({token});
}
I generate my token this way :
const generateToken = (_id, userID) => {
console.log('Signing token for ID ', _id);
console.log('Secret key is ', process.env.JWT_KEY);
const token = jwt.sign({ _id, userID}, process.env.JWT_KEY, {
expiresIn: "30d",
});
console.log('Signed token: ', token);
return token;
};
I try to store my token in my "userInfo" State .. but only username and password is displayed not token ..It works before .. but I don´t know why it´s not working anymore ^^ I´m completely at a loss
I hope someone sees the error
my Console gives me the detail:
TOKEN
undefined
Return the token with the token key at the end of your login function in the REST API, since that's how you access it in your frontend.
return res.status(200).json({token: token});