I am trying to implement a login function in my ReactJS component where I make two API calls using Axios. The first API call sends the user’s email and password to get a JWT token in response. The second API call uses this token to fetch user-specific notes from the backend. However, while this works correctly in Postman, my ReactJS code returns an empty array for the notes.
Here is my code:
async function login(event){
event.preventDefault();
setUser({ email: "", password: "" });
console.log("login email: " + user.email + " & password " + user.password);
// Request to login and get token in response
try {
const loginResponse = await axios.post('http://localhost:5000/auth/login', {
emailid: user.email,
password: user.password
});
console.log('login successful: ', loginResponse.data.token);
const token = loginResponse.data.token;
console.log("token value: " + token);
// Use token to get all notes of user
let config = {
method: 'get',
maxBodyLength: Infinity,
url: 'http://localhost:5000/api/read',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: QueryString.stringify({
'email': user.email
})
};
const allNotes = await axios.request(config);
console.log("data ", allNotes);
// Further state updates
// setNotes(allNotes);
// setAuthenticated(true);
} catch (error) {
console.log("Login Error: " + error);
}
}
When I run this code, allNotes.data
logs an empty array, whereas in Postman, the same API calls return the expected data.
- Verified that the token and user email are correctly passed in the headers and body.
- Checked the backend API using Postman, and it works as expected.
- The first API call to get the token works correctly.
- The second API call to get the notes using the token returns an empty array in my ReactJS code but works correctly in Postman.
What could be causing this discrepancy? How can I ensure the second API call returns the correct data in my ReactJS code?
H1 s1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
As shown in examples in doc, Axios GET-requests should either be on this form:
axios.get('/user?ID=12345')
or this form
axios.get('/user', {
params: {
ID: 12345
}
})
Hence, you’ll need to replace data
with params
in order to pass the parameters.
let config = {
method: 'get',
maxBodyLength: Infinity,
url: 'http://localhost:5000/api/read',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
email: user.email
}
};
1