Node.js Web Server

Installing Node.js

curl -sL https://deb.nodesource.com/setup | sudo bash -
apt-get install nodejs

Installing Extra Tools

apt-get install nano

Making a new project

cd ~
mkdir web
cd web
npm init
npm install express --save

Making a new project

nano index.js

# Remember [CTRL][X] then [Y] to quit

Making a new project

nano index.js

# Remember [CTRL][X] then [Y] to quit

Simple Web Server

var express = require("express");
var app = express();

app.get("/", function(req, res) {
    res.send("Hello!");
});

app.listen(80, function() {
    console.log("Listening on port 80!");
});

Run with `node index.js` and go to your server's IP and look at the output!

Challenges

  • Add more routes (pages).

HTML Files

mkdir html
cd html
nano index.html
cd ..
nano index.js

Serving HTML Files

res.sendFile("index.html");

Request Queries

app.get("/hello", function(req, res) {
    if (req.query.name) {
        res.send("Hello There " + req.query.name + "!");
    } else {
        res.send("Hello!");
    }    
});

Now run and go to /hello?name=Jeff

Path Paremeters

app.get("/hello/:name", function(req, res) {
    // req.params
});
Made with Slides.com