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 nanoMaking a new project
cd ~
mkdir web
cd web
npm init
npm install express --saveMaking a new project
nano index.js
# Remember [CTRL][X] then [Y] to quitMaking a new project
nano index.js
# Remember [CTRL][X] then [Y] to quitSimple 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.jsServing 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
});deck
By Jake Walker
deck
- 642