Category: node.js

After learning about cookies, lets look briefly about sessions in Express applications.

If you’ve ever worked on any serious web application, you already know the importance of session. Creating session for logged in users, tracking the shopping cart items, storing the URL for redirect etc are some of the basic uses of sessions.

Here we check if the req.session.name has been set. If set, we show link to logout and also show current value present in the session variable. If the user is coming from /logout page, then we show “user logged out!” message.

Note: Make sure to have good session secret key – a combination of alphanumeric plus special characters. And make sure not to reveal it to anyone. Because, using this secret key / hash, someone with bad intention could possibly revoke the session and use your application as an authentic user, if care is not taken!

The main difference with cookie and a session is – session is stored on the server side and cookie on the client side.

Help Us ->

Cookies are one of the important recipe for building an effective web application.

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website you are surfing and stored in a user/client computer. Every time the user loads that website again, the browser sends this cookie back to the server to notify the website of the user’s previous activity.

This way, using cookie, we could track user activities like her navigational behaviors, previous purchases on our site or previous leads etc.

Using express’s cookieParser() middleware we can enable working with cookies.
Once the user navigates to /user/someUserName URL, the cookie is set with the name username and the value is actually fetched out of the request object’s params.

You could remove a cookie by using clearCookie method of response object.

Once the cookie has been removed, you can set it again explicitly using Chromes console window.
Type: document.cookie = “username = Microsoft”
now refresh the browser, and you’ll see Microsoft being displayed!

For list of all supported middleware, visit senchalabs
Also check the list of all the 3rd-party middleware supported by Connect.

Note: Ordering of these middleware is very important.For Example:1. You can only override method after you’ve parsed the body, so methodOverride() must come only after bodyParser()2. Similarly, session middleware depends on cookieParser(), so session middleware must come only after cookieParser()

As your application becomes popular you’ll need middlewares to handle csrf( Cross-site request forgery ), DDos attacks etc. Also it’s very important to validate the user requests before you allow the user request to fetch the data from your database. Learn to use middleware properly, and I’m sure, it’ll be a life-saver for your application.

Here we have an array of objects – which in real-time application we get from a database ( Ex: MongoDB ). Now we define a route, and get two params in a single URL. By fetching and parsing those two params, we pass it to slice method of array and get array objects within the range/limit. Also note the use of response in json formatting while sending the data using response object.

we enter our regular expression between two forward slashes. And to escape the forward slash present inside our regular expression, we make use of escape character i.e., a back slash. After /user/ we can have zero or more digits, after that an optional edit keyword followed by an optional trailing forward slash.

When we request information of particular user by using his username in the URL, it fetches the username using request object and displays appropriate message.Example: If the user requests /user/Satish it’ll output Satish’s profile!

Public Folder

If we put some files inside our public directory, it would be convenient if some middlewares fetch the files directly upon user request, instead of writing routes for all those files. Connect module which is a dependency of Express web framework takes care of this.

Inorder to parse the HTML page, you’ll need bodyParser middleware. Once you have it in place you can get form field entries and use it to insert the data into database or simply display as in our case with this example.

By getting the unique userId of the user, you could fetch the data from database and make changes and update the information using Put request. Similarly, using the unique userId of the user, you could select and delete the information about the user!

Separating Route Files
As your application grows, its hard to keep the code cleaner and maintainable, so it’s always a good idea to separate these kind of information from the main application file. So we create a file called routes and include it as a local module in our main application file.

Help Us ->

You may often want different settings for development environment and a different settings in the production environment. Also you could keep pushing the files to server for testing. So you’ll need to test your application in two different environments: development & production

In situations like this, you could have environment specific configurations using express. In this video tutorial, I’ll be walking you through setting up configurations for these environments using Express, web framework of Node.js.

Here we create an express object, using which we set the configurations.
First we set the port number to whatever is set by the server – which is present in the environment variable process.env.PORT if it is not set use 3000 as port number.
Next, assign views a directory: root directory( __dirname ) and views folder. You could create any folder inside root and assign it to views. Then, set default view engine as Jade. Next we enable the view cache – btw View caching is useful in production environment.

Development Environment
app.js

1
2
3
4

// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

Here we could list all the settings needed for our development environment.

Help Us ->

Mixins in Jade are much like functions/methods in many other programming languages.

Basically, if you’re repeating your code at many places, you could place that code inside a mixin and replace your code with the mixin call. This would make your code cleaner and maintainable over long run.

Note: Clearly, in real-time applications the array or object come from the database.Example: You might encounter the situation to list out all the users in your list and list of all the participating companies. Or list of all companies someone has worked at. In such cases you’ll get an array of objects which you need to out put to the user in a well formatted manner. In situations like this, mixins are a great tool to have, to avoid the necesity to repeat your code allover your application.

Have all your mixins in a single file and then include that file wherever you are calling your mixins.

Help Us ->

After going through the basics of Jade, lets learn about loops and conditional statements in Jade.

Note: Since most text editors designed for web remove the indentation(and some retain only new line characters), thus compressing the file and optimizing it for the web use. But this doesn’t serve any good for writing Jade. Because indentation is at the heart of Jade syntax!

So in this tutorial, we are using a Chrome extension called Jade Editor to illustrate loops and conditional statements. You can simply test your code in this Google Chrome extension and then copy over the code to your actual file. This would even help reduce the complicated errors in lengthy files.

Help Us ->

Lets learn some of the basics of Jade Template Engine. Jade is the default template engine for Express Web Framework of Node.js Also note that, Jade and Express are open source product of the same company, so go very well with each other!

Using template engine might seem pointless in the beginning, but if you’re building a large-scale application, it’s a handy tool and you’ll feel good about your decision to use one for your project.

This would let your application know that you’ll be using Jade as Template Engine. This way, you need not mention the Template Engines file extension each time.

Jade File: Indentation
index.jade

1
2
3
4

html
head
title Technotip
body

html
head
title Technotip
body

Would output

1
2
3
4
5

<html>
<head><title>Technotip</title></head>
<body>
</body>
</html>

<html>
<head><title>Technotip</title></head>
<body>
</body>
</html>

Indentations in Jade decide which element(s) is/are a child off which element.

Jade File: Variable
index.jade

1
2

- var name = "Love For Design"
p= name

- var name = "Love For Design"
p= name

and

Jade File: String. Minus sign significance
index.jade

1
2

- var name = "Love For Design"
p #{name}

- var name = "Love For Design"
p #{name}

Out put Love For Design on the browser, inside a paragraph tag.

Jade File: Code Interpretation – REPL
index.jade

1

p #{ 1 + 5 }

p #{ 1 + 5 }

This outputs 6 on to the browser inside a paragraph tag.

Jade File: String Length Management
index.jade

1
2
3
4
5
6
7

p
| My Name is Satish
| I Love web development
| I love helping people
| by teaching them whatever I know
| I believe, this is a good cause of
| spreading knowledge.

p
| My Name is Satish
| I Love web development
| I love helping people
| by teaching them whatever I know
| I believe, this is a good cause of
| spreading knowledge.

This would treat the entire string as a single line text, and out put looks like:My Name is Satish I Love web development I love helping people by teaching them whatever I know I believe, this is a good cause of spreading knowledge.

Jade File: Id’s and Classes
index.jade

1
2

div#wrapper
p.highlight I Love Node.js

div#wrapper
p.highlight I Love Node.js

This would apply the id wrapper to div and highlight class to p tag.

Jade File: Multiple id and class
index.jade

1
2

div#wrapper.content.highlight
p I Love Node.js

div#wrapper.content.highlight
p I Love Node.js

We could even assign multiple id’s and classes to a html element.

Jade File: Anchor Tag
index.jade

1

a(href="/about", rel="nofollow") Satish

a(href="/about", rel="nofollow") Satish

This would wrap the word Satish with anchor tag and nofollow attribute.

Help Us ->

As we have already started using Web Framework of Node.js i.e., Express, we’ll be building considerably large web applications, and it needs us to edit the files often. We need to restart the server every time we save changes to main application file. This would start consuming lot of time and sometimes we may forget to restart the server and may think that our application file has bugs, as it doesn’t reflect on the browser!

To solve this issue, we could make use of some dependency modules which listens to the changes we saved to these main node application file and restarts the server automatically by itself.

Now whenever we make changes to app.js file, and hit save, nodemon object listens to the new changes we saved, and restarts the server. This way we save a lot of time while in development mode, and directly see the changes reflect on our web browser almost immediately upon refreshing the web browser.

Note: Changes to files in public directory and the .jade files doesn’t require a server restart to reflect on the browser. These are files which are simply rendered upon calling, so whatever is present in these files are [compiled and] shown whenever there is a request to it.