girlcodeakl / girlcode2018-term2

Girl Code project
0 stars 0 forks source link

Administration tool for deleting posts #33

Closed mgatland closed 6 years ago

mgatland commented 6 years ago

what's this?

Let's make a tool for deleting posts. It will let the user type in the id number of a post, and delete it. We will also make them put in a password, and we will only delete if the password is correct.

step 1

Make a new page called delete.html and start off by copying everything from post.html. Then change it:

If you change the class of an input, you have to also change the class in the javascript so it still links up.

When we save the values into the data object, the name we choose will be the name the server sees. For example data.message = … will give the server something in request.body.message.

now on the server

In index.js teach the server how to respond to this new kind of request.

Add this code:

function deleteHandler(req, res) {
   console.log("client wants to delete this post: " + req.body.postId );
    //code goes here
   res.send("ok");
}
app.post("/delete", deleteHandler);

CHECK: Restart the server, try deleting a post. It won't delete yet, but you should see the message "client wants to delete this post…" appear in your console.

delete the post

We need to delete the post from two places: The server has its own list, and there's another copy in the database.

delete the server's copy

let postIdNumber = parseInt(request.body.postId);
posts = posts.filter(post => post.id != postIdNumber);

Try deleting a post -- it should delete!

Try restarting the server. The server gets all the posts from the database, so the deleted post comes back :/

delete the post from the database too

  databasePosts.deleteOne({ id : postIdNumber })

Test the post is gone for good, no matter what you do.

Security check

Let's make it only delete the post if you entered the right secret code. Use an if statement, and put all the deleting stuff inside it.

if (req.body.password === "1234") {
 //things that happen if the password was correct
} else {
  console.log("Wrong password");
}