X

Visual Studio Node.js, creating express applications

nodejs

Here is a simple walk through of creating a express application with node.js using Visual Studio (NTVS).

First lets launch visual studio and go to the JavaScript section and select the Blank Express Application.

Once selected, I have named my application SimpleExpress, Visual Studio will start creating the skeleton of the project for you, and if you do not have express it will start downloading it for you using NPM.

Click on Yes, and it will download all the dependencies.

Once completed you cant hit F5 on Visual Studio to build the solution and launch the new browser.

You may get an error though. The error says doctype 5 is deprecated, you must now use doctype html, lets look for the layout.jade file in the view folder and change the first line from 5 to html like this

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

Now when you hit F5 your solution should build and you will be able to view the site.

If we look into the code of index.js inside of routes folder we find.

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

The first parameter is requesting for the index view and the second parameter is a json object that passes in the data of title, kind of like an anonymous ViewModel that you may pass with your ASP.NET MVC framework for the view to render.

Lets add another parameter into the json object.

exports.index = function(req, res){
  res.render('index', { title: 'Express', username: 'Taswar Bhatti' });
};

Now we can edit the index.jade file and read the parameter

extends layout

block content
  h1= title
  p Welcome to #{title},  #{username}

There is also another way of sending data to a client by using resources and not using a view or the layout.
If you open users.js file you will see

exports.list = function(req, res){
  res.send("respond with a resource");
};

And if you go to your http://localhost:1337/users

The response send back is just a stream of text, rather than html with a layout etc.

I have just touched the surface of express with node, in future blog post I will go more in details of using express to build an application.

Categories: Node visual studio
Taswar Bhatti:
Related Post