the API for login provides userId,name and sessionId (for Cookies) when parameters are given in JSON body. here is the example code via POSTMAN
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Cookie", "sessionId=eyJhbGciOiJIUzI1NiJ9.MTY4OTI0Nzk3MDcwNzBsdGlheGYycThuaA.oD6XM_s3tAdv6eBxjierxoH_KK-Mc1qvyOR5CpDStMY");
var raw = JSON.stringify({
"email": "[email protected]",
"password": "newPassword"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://mcqapi.onrender.com/api/users/login", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
the sessionId myHeaders.append is being given in response by API every time but how will it work for the other web pages of the website e.g. I have this code on the other page of the website but it will only work if there are cookies in the header
fetch("https://mcqapi.onrender.com/api/topics", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
const topics = data.map((topic, index) => `${index + 1}. ${topic.questionTopic}`);
const titleElements = document.querySelectorAll('.title');
titleElements.forEach((element, index) => {
element.textContent = topics[index];
});
})
.catch(error => console.log(error));
I have tried saving sessionId in localstorage and retrieve its value for other page but it didn't work
fetch("https://mcqapi.onrender.com/api/topics", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cookie': 'sessionId=' + localStorage.getItem('sessionId')
}
})
.then(response => response.json())
.then(data => {
const topics = data.map((topic, index) => `${index + 1}. ${topic.questionTopic}`);
const titleElements = document.querySelectorAll('.title');
titleElements.forEach((element, index) => {
element.textContent = topics[index];
});
})
.catch(error => console.log(error));