I want to set the authenticate token as a key-value pair in a react-js like x-access-token(key) = JWToken.value
I am generating the token like following in the backend:
module.exports = middlewares = {
authenticateToken: async (req, res, next) => {
try {
if (
!req.headers["x-access-token"] ||
req.headers["x-access-token"] === ""
) {
return res.failed(401, "Key x-access-token not found");
}
const token = req.headers["x-access-token"];
const data = jwt.verify(token, keys.JWToken);
if (!data) return res.failed(401, "Invalid token");
req.data = data;
next();
} catch (error) {
return res.failed(500, "Internal server error", error);
}
},
};
How can I do that because whenever I send the request to the protected route I am getting the Unauthorized error which is obvious.
the data stored in the local storage:
{flag: true, code: 200, data: ..., message: "Logged in successfully", error: null}
code : 200
data :
JWToken : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzMjQ9MzRjOTQxNTMxMTYzZDIwMDFhYSIsImlhdCO8MTY2xzgzMjcyNywiZXhwIjoxMjk1Mzg5NjUzfQ.JOO1Cy8-7M4_kFHxRyK6g48s9vR2xXSB3pOpAzw3UgS"
user : {_id: "6324734c941531163d2001aa", email: "[email protected]", phone_number: "1334567891"}
email : "[email protected]"
is_verified : true
role : "admin"
_id : "6324734c941531163d2001aa"
error : null
flag : true
message : "Logged in successfully"
The package action file:
export const createPackage = (packageData) => async (dispatch, getState) => {
try {
dispatch({ type: PACKAGE_CREATE_REQUEST });
const {
adminLogin: { adminInfo },
} = getState();
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `${adminInfo.data.JWToken}`,
},
};
const { data } = await axios.post(
"http://localhost:8000/v1/package/add_package",
packageData,
config
);
dispatch({ type: PACKAGE_CREATE_SUCCESS, payload: data });
} catch (error) {
dispatch({
type: PACKAGE_CREATE_FAILURE,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
CodePudding user response:
Can you try once like this?
const config = {
url: "http://localhost:8000/v1/package/add_package",
method: "POST",
data: packageData,
headers: {
"x-access-token": adminInfo.data.JWToken,
}
};
const { data } = await axios(config).catch(console.error);