Skip to content
Amir Hossein Seyhani edited this page Jul 21, 2017 · 8 revisions

Routing

At first we have to pull spring96 branch from repository

Then we have to add our routes Here we need two route:

  1. route to render the game page

     router.get("/game", showGamePageController)
    
  2. route to submit the user's high score

     router.post("/game", submitScoreController)
    

Get route

Here is our first contact with callbacks in JS.


Here we say the router if it see the "/game" path, it have to call showGamePageController function.

router.get("/game", showGamePageController)

Next let's implement showGamePageController function.

Here it has two arguments req(request)and res(response), which are objects that passed when called by router

At first we get username from request cookie. var savedUsername = req.cookies.username;

Then we have find high score of the user with this username (if exists in database) and then use render function. So we define a function for this:

function renderTetrisGamePageWithUserScore(err, storedUserScore) {
    res.render("game", {score:savedUsername});
}

Post route

Here we catch post request:

router.post("/game", submitScoreController);

SubmitScoreController :

function submitScoreController(req, res){

We get user name and high score from request:

var savedUsername = req.body.username;
var score = req.body.score;

Now we need to somehow store user data wich is consist of username and high score, to handle this we have to defined Score model (database and models will be explained later) So at first we have to import score model:

var Score = require("../models/score");

Score have a findOne method :

findOne(options, callback)

It finds the document in database wich match options argument

Clone this wiki locally