I make web application with React, Express, MongoDB.
And, I want to pass jwt token with header.
But, I pass it, get 401 error (Unauthorized).
In login actions.js :
export function login(username, password) {
return function(dispatch) {
axios
.post(`${API_URL}/auth/login`, { username, password })
.then(res => {
dispatch(loginSuccess(res.data, username));
const token = res.data.token;
axios.defaults.headers.common["Authorization"] = token;
history.push("/");
})
.catch(err => {
if (err.response.status === 401) {
dispatch(loginFailure(err));
}
});
};
}
And, In my post.js in server :
getToken = function(headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(" ");
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
...
// Save Post
router.post("/", passport.authenticate("jwt", { session: false }),
function(
req,
res,
next
) {
var token = getToken(req.headers);
if (token) {
Post.create(req.body, function(err, post) {
if (err) return next(err);
res.json(post);
});
} else {
return res.status(403).send({ success: false, msg: "Unauthorized." });
}
});
How I do fix it? + Login is success
Include your token as authorization key as below.
Try res.header('x-auth', token).send() 'x-auth' can be anything. Above is used to set token in the headers
First of all when you login and send username and password to backend then in response you get token_id. now try to token store in session_storage and redirect to your desire page. now you take token_id in your desire page and store one variable as like..
now you have token and pass in the header and get data in response
note : you should set blank items array in initial setState as like
how-to-pass-header-jwt-token-with-axios-react ???
This is example for create axios instance with API Base URL and JWT_TOKEN globally and access it for different API calls
step 1 : create static instance for axios
this is the second setep access axiosInstance already create and use it with dynamic REST API calls
step 2 : access static instance and bind API_URL to base URL
API URL = BASE_API_URL + API_URL and single JWT_TOKEN for all and this very clean , clear and working.