Week 06 → Day 027 → Wednesday → September 13, 2017

Index Client and Server – 0:00
Node.JS and Express – 4:31
HTTP requests and responses –
HTTP headers and status codes
Request parameters
API design and development

Resources

Node – node.js
Express – expressjs.com
Node File System module – https://www.w3schools.com/nodejs/nodejs_filesystem.asp
HTTP headers – https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

Client and Server ━ 🗣 0:00

Client Server
Code runs on client's machine Code runs on server
Makes HTTP GET request Handles HTTP GET request
Renders or processes response data Generates/sends response data

Node.js ━ 🗣 4:31

Node.js is an open-source, cross-platform JavaScript run-time environment for executing JavaScript code server-side. – Wikipedia

Client-side JS NodeJS
Runs on client's web browser Runs in node.js process
Has window, document objects No window, document objects
Interfaces with HTML and DOM No HTML, no DOM, no selectors, etc.
Uses AJAX to make HTTP reqs Can directly open connections
Uses script tags to split code into files Uses modules to spplit code into files

Express.js

Express.js, or simply Express, is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It is the de facto standard server framework for Node.js. – Wikipedia

Web Applications

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

APIs

With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.

Setting Up Express ━ 🗣 8:20

// package.json

dependencies: {
    body-parser: ^1.17.2,
    express: ^4.15.4
}

Import express module and initialize

// app.js
const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000, () => {
  console.log('Example app listening on port 3000!')
})

This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

$ node app.js

Nodemon ━ 🗣 18:01

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development.

$ nodemon app.js

File System module ━ 🗣 19:45

The Node.js file system module allow you to work with the file system on your computer.

To include the File System module, use the require() method:

// app.js
const fs = require('fs');

Common use for the File System module:

Read files

fs.read method is used to read files on your computer.

server.get('/file.html', (req, res) => {
    fs.readFile('file.html', 'utf8', (err, contents) => {
        if (err) throw err;
        res.send(contents);
    });
});

Create files

fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:

fs.appendFile('mynewfile1.txt', 'Hello content!', (err) => {
  if (err) throw err;
  console.log('Saved!');
});

fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:

fs.open('mynewfile2.txt', 'w', (err, file) => {
  if (err) throw err;
  console.log('Saved!');
});

fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

Update files

fs.appendFile() method appends the specified content at the end of the specified file.

fs.writeFile() method replaces the specified file and content.

Delete files

fs.unlink() method deletes the specified file:

fs.unlink('mynewfile2.txt', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

Rename files

fs.rename() method renames the specified file:

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

JSON (JavaScript Object Notation) ━ 🗣 25:20

JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON.stringify ⋰ JSON.parse ━ 🗣 28:20

const str = JSON.stringify({ a: 3 }) // '{"a":3}' serializes the object

JSON.parse(str) // { a: 3 } deserializes back to an object
app.get('lesson-plan', (req, res) => {
    const lessonPlan = {
        title: 'Node.js and Express',
        tagline: 'Server-side JavaScript'
    };
    res.send(JSON.stringify(lessonPlan));
});

Headers ━ 🗣 33:00

HTTP headers allow the client and the server to pass additional information with the request or the response.

Headers can be grouped according to their contexts:

  • General header: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body.
  • Request header: Headers containing more information about the resource to be fetched or about the client itself.
  • Response header: Headers with additional information about the response, like its location or about the server itself (name and version etc.).
  • Entity header: Headers containing more information about the body of the entity, like its content length or its MIME-type.

Content-Type ━ 🗣 33:53

Setting the content-type meta data:

res.set('Content-type', 'application/json');
res.type('json');

Shortcut:

res.json(lessonPlan); // Serializes JSON and sets content-type

Query string ⋰ Request parameters ━ 🗣 37:00

https://en.wikipedia.org/wiki/Query_string

A query string is the part of a uniform resource locator (URL) containing data that does not fit conveniently into a hierarchical path structure.

https://www.google.com/search?q=hello
app.get('/greet-me', (req, res) => {
    const name = req.query.name;
    res.send(`<h1>Hello ${name}!</h1>`);
});
http://localhost:3000?name=frank

Hello frank!

Validating request parameter ━ 🗣 45:32

app.get('/greet-me', (req, res) => {
    const name = req.query.name;
    if (!name) {
        res.send({ error: 'Must provide a name' });
        return;
    }
    res.send(`<h1>Hello ${name}!</h1>`);
});

Status codes ━ 🗣 46:38

const STATUS_USER_ERROR = 422;

app.get('/greet-me', (req, res) => {
    const name = req.query.name;
    if (!name) {
        res.status(STATUS_USER_ERROR);
        res.send({ error: 'Must provide a name' });
        return;
    }
    res.send(`<h1>Hello ${name}!</h1>`);
});

URL parameter ━ 🗣 49:22

Instead of using a query string http://localhost:3000?name=frank to accept a paramteter, you can also use a URL parameter http://localhost:3000/frank

app.get('/greet-me/:name', (req, res) => {
    const name = req.params.name;
    ...
}

POST Requests ━ 🗣 51:35

POST requests allow the client to create data. POST request parameters are sent as JSON in the request body.

{
    'tasks': 'Do laundry'
}
const tasks = [];

server.post('/tasks', (req, res) => {
    const task = req.body.task;
    if (!task) {
        res.status(STATUS_USER_ERROR);
        res.json({ error: 'Must provide a task' });
        return;
    }
    tasks.push(task);
});

Parse JSON bodies ━ 🗣 57:00

const bodyParser = require('body-parser');

server.use(bodyParser.json());

Responding to POST requests ━ 🗣 58:11

const tasks = [];

server.post('/tasks', (req, res) => {
    const task = req.body.task;
    if (!task) {
        res.status(STATUS_USER_ERROR);
        res.json({ error: 'Must provide a task' });
        return;
    }
    tasks.push(task);
    res.json({ tasks }); // Sending the tasks array in an object
});

results matching ""

    No results matching ""