Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

Introduction


A quick over of three ways to create a node.js application

Creating an Application Base

Method 1

Simply create your .js files and a launch.json file.

Run your scripts using node <file>.js

You might want to add a package.json file to ease the execution of your application.  A basic package.json file looks like this

package.json
{
  "name": "sample2",
  "version": "1.0.0",
  "description": "quick web demo",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "Selvyn",
  "license": "ISC"
}


Method 2

Use the npm init command.  It will create the package.json file for you after prompting you to answer a few questions.  You still need to create your basic .js files.


Method 3

Using the npm express-generator.

  1. Install express-generator using the command npm install -g express-generator
  2. Create an app using npm init
  3. Add express files to your project using the command npm install express --save


Adding files to the project

Add the following code to your default root file (normally index.js but could be any file you choose)

index.js
var express = require("express");
var app = express();

app.listen(3000, () => {
   console.log("Server running on port 3000");
});


When you run this app you will see the message "Cannot GET /".  If you check the developer's tools console output you will see the following error "GET http://localhost:3000/ 404 (Not Found).  You are seeing this message because you have not set up any event handlers (your application has no endpoints)

Setting Request Handlers

A Web Server receives Requests, processes them, and returns a Response.  We need to establish route handling in our application to handle these Requests. 

When developing modern applications we expose what are called ReSTful web services.  These Requests are a GET request that gets data, a POST request that sends data securely, a PUT request that updates data, and a DELETE request that deletes data.

As well as deciding on the Requests, we also need to decide on we will respond with a Response to Requests.

Let's create a simple GET request that says "hello world"

index.js
app.get("/sayhello", (req, res, next) => 
{
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.send("Hello World");
});




  • No labels