Writing the frontend for it
Course: Authentication - chapter 11
Until now, we’ve been using POSTMAN to send out all of our requests.
Now, lets create a full stack application. Lets write the frontend that lets you
- Signup
- Signin
- Get your information
- Logout
Writing the frontend
Section titled “Writing the frontend”Create a `public/index.html` file
mkdir publiccd publictouch index.htmlCreate a `signup section`
<div> Signup <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button onclick="signup()">Submit</button></div>Create a `signin section`
<div> Signin <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button onclick="signin()">Submit</button></div>Create a `User information` section
<div> User information: <div id="information"></div></div>Create a logout button
<div> <button onclick="logout()">Logout</button></div>Writing the onclick handlers
Section titled “Writing the onclick handlers”Add the axios external library
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.7.7/axios.min.js"></script>Write the signup function
async function signup() { const username = document.getElementById("signup-username").value; const password = document.getElementById("signup-password").value;
const response = await axios.post("http://localhost:3000/signup", { username: username, password: password }) alert("Signed up successfully");}Write the signin function
async function signin() { const username = document.getElementById("signin-username").value; const password = document.getElementById("signin-password").value;
const response = await axios.post("http://localhost:3000/signin", { username: username, password: password });
localStorage.setItem("token", response.data.token);
alert("Signed in successfully");}Write the logout function
async function logout() { localStorage.removeItem("token");}Write the `getUserInformation` function
async function getUserInformation() { const token = localStorage.getItem("token");
if (token) { const response = await axios.get("http://localhost:3000/me", { headers: { Authorization: token } }); document.getElementById("information").innerHTML = response.data.username; }}Updating the backend
Section titled “Updating the backend”Lets serve the index.html file directly from the backend
Approach #1
app.get("/", function(req, res) { res.sendFile("./public/index.html")})Approach #2
app.use(express.static("./public"))
Firing the getUserInformation call
Section titled “Firing the getUserInformation call”Call the `getUserInformation` function when the page loads
getUserInformation();Assignment
Section titled “Assignment”Conditionally render the logout or the signin/ signup pages based on if the user is already logged in or not