I have defined the following function to use fetch to make post or get requests:
async function postData(url = "", data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
async function getData(url = "") {
// Default options are marked with *
const response = await fetch(url, {
method: "GET", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
credentials:"include",
headers: {
"Content-Type": "application/json",
},
});
return response.json(); // parses JSON response into native JavaScript objects
}
Now I want to use it to perform a login first and if the login is valid then to retrieve the user data:
$("#login_form").submit(function(e) {
e.preventDefault();
let email= $('#username_login').val();
let password= $('#password_login').val();
postData("http://localhost:4000/api/login", { email:email, password:password }).then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
if(data){
getData("http://localhost:4000/api/profile").then((data)=>{
console.log(data);
});
}
});
});
});
The first POST request works fine (I receive what is expected). The second one is not working because it is not sending back the cookies set by the response of the first request. I am pretty much sure that this is related to the fact that the second fetch is initiated before the first complete but cannot see how to fix it