'How can I modify this code to make it able to delete and log out the user?
I am working with a web server and client currently and I want my website to have a dropdown menu that allows the user to view their profile, log out of their account, or delete their account. I have the javascript all set up so that they can view their code but I am not sure how to set it up so that it can delete their profile and log them out of the website. Below is what I have in order to access their data and display it on the main page of my website. The problem is that they tutorial does not say anything about logging out of a site or completely getting rid of user data.
const displayAccountItem = document.querySelector("#displayAccountItem")
displayAccountItem.addEventListener("click", async(e) => {
e.preventDefault()
const token = localStorage.getItem("token")
//const url = "http://localhost:3001/users/me"
const url = 'https://<<your-API-server-domain>>/users/me'
const options = {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
}
let response = await fetch(url, options)
if (response.ok) {
if (response.status === 200) {
const data = await response.json()
const contentArea = document.querySelector("#contentArea")
contentArea.innerHTML = `Name: ${data.name} <br>Email: ${data.email}`
}
} else {
console.log("HTTP-Error: " + response.status)
}
})
Solution 1:[1]
If the response returns the Status code as 4XX you can simply clear the localstorage and redirect the user to the login page or the page which is expected to be rendered.
For clearing the localstorage you can do
localStorage.clear();
Keep in mind that this will clear all the values in the localStorage. If you want to remove only token the use
localStorage.removeItem(keyname)
If I have missed any of your condition kindly let le know.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nikhil |