NodeJs1: Server request/responses with Postman, CORS, and JWT authentification

NodeJs is a server-side javascript environment for app development.

We use ExpressJs, an open-source NodeJs framework, to handle HTTPS requests with routing support.

The REST (Representational State Transfer) API exchanges data between applications through HTTPS methods like GET, PUT, POST, and DELETE. (Client-> API -> Database -> Database data).

To start a NodeJs server we import/require express methods, each route will include an endpoint and its handler function:

- npm Init         //We start up a package.json file

//The endpoint sets where the request and response is gonna take place
const express = require('express');
const app = express();

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

//listen() sets the localhost: endpoint 
app.listen(3000, () => console.log("Server is up and running"))

//node server.js to start the server

The endpoint is the part of the URL that comes after /.

Contrary to React, the server needs to re-start in order to update, to avoid that we npm i nodemon.

chevron-rightAlternative to nodemon: Supervisorhashtag

Supervisor is a Node.js process manager, it monitors and restarts the the application on crashes or file changes. Typically used in production, it offers similar functionality to Nodemon but is not a dependency or library.

For more information on using fetch in client-server request/response interactions, see this link.

Postman is a scalable testing tool, it can retrieve information sent by the server routes.

Queries are the url part that comes after a ?...=, it is used to pass information from the endpoint to the server routes.

Postaman Get method for a URL with query
chevron-rightMultiple queries for Math operations routeshashtag

To add multiple queries to the url we use &:

Queries values are strings by default, we convert them for math functions.

Parameters are properties attached to the URL, prefixed with (:) on the endpoint, and requested with req.params.___.

Postman allows testing of custom headers for use in server.js.

Tests for server headers

For more information about Middlewares check here.

Modify a JSON file with Postman POST data

To body-parse request body elements we use() the express.json() built-in middleware. We install file-system (fs) which will allow us to update server files.

We request the body from Postman Post and update the imported JSON array using fs.

Postman POST and updated JSON (with changed ID)

Both Post and Put Postman methods can update and create elements, Put is idempotent, its results remain the same not matter how many times it's repeated.

chevron-rightPUT and DELETE method update on JSON file hashtag

To update the JSON file with the Postman POST body, we filter both its ID and its parameter so it keeps the updated object ID.

To DELETE a JSON element by its ID parameter, we filter() it and use the matching element index to splice().

CORS and JWT autentification

CORS, Cross-Origin Resource Sharing, allows servers to set specific origins for their request. Origins are defined by their protocol HTTP and port number.

HTTP is a stateless protocol, it won't record any request data, so to authenticate the user and to share data between the browser and server we used sessions.

Session objects track users by comparing their cookies (string files downloaded on website access) to the ID session. When users make a request (log in) it checks if they have an already open session and what permits they have.

Sessions need storage space and extra security when sent to the server, they make the app harder to scale, and it's hard to implement on apps that contain many back-end micro-services or don't use the browser for their cookies.

Sessions cookies and session ID

The JSONWebToken (JWT) registers the user directly to the app without any sessions. JSON stands for Javascript Object Notation, a text-based data format transferable between all languages and standard syntax for APIs.

The JWT is made of clains (string sections) separated by a comma, clains are encoded in code-64.

The first header clain contains the hashing algorithm and the token type. The second contains the JSON object sent to the user, visible to anyone. The third is a secret hash, kept by the server and it resets if the original request changes.

JWT token

Implementing JWT registration to the server

The JWT user server will have this structure.

Check the CORS section to know more about the configuration.

The /user route will handle all user server calls, check the Express routing section for more.

chevron-rightServer routing, bcrypt and File-System moduleshashtag

We request the user destructed form data to update/check the database, using bcrypt for the password and fs to edit the database js file.

Created Post user in teh JSON database and JWT user response.send()

We set the utilities following the JWT section

We store the JWT key in a safe place, like an env file.

Sign-in JWT and JWTBearer on Postman with code 200 res.send()

Last updated