Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[nodejs] iterate through fetch response headers

https://github.github.io/fetch/#Headers

        const response = await fetch("https://example.com/api")

        for (const [key, value] of response.headers) {
            console.log(key, value)
          }

An alternative would be forEach()

        response.headers.forEach((value, key) => {
            console.log(value, key)
        })

Or using the entries() iterator (ES8)

          const headerIterator = response.headers.entries()
          console.log(headerIterator.next().value)
          console.log(headerIterator.next().value)

To add a new header just use set()

response.set(key, value)

[nodejs] Basic Node and Express

These are my notes while doing the course APIs and Microservices on https://www.freecodecamp.org. I highly recommend it if you prefer to try things directly rather than watching videos.


Node.js is a JavaScript runtime that allows developers to write backend (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules (small, independent programs) that help facilitate this purpose. Some of the core modules include:

  • HTTP: a module that acts as a server
  • File System: a module that reads and modifies files
  • Path: a module for working with directory and file paths
  • Assertion Testing: a module that checks code against prescribed constraints

Express (not included by default) runs between the server created by Node.js and the frontend pages of a web application. Also handles the app’s routing.

https://github.com/freeCodeCamp/boilerplate-express/


Start a Working Express Server

Let’s serve our first string! In Express, routes takes the following structure: app.METHOD(PATH, HANDLER). METHOD is an http method in lowercase. PATH is a relative path on the server. HANDLER is a function that Express calls when the route is matched.

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

Serve an HTML File

You can respond to requests with a file using the res.sendFile(path) method. This method needs an absolute file path. Use the Node global variable __dirname to calculate the path.
Send the /views/index.html file as a response to GET requests to the / path.

let absolutePath = __dirname + "/views/index.html";

app.get("/", (req, res) => {
  res.sendFile(absolutePath);
});

Serve Static Assets

Using express middleware to serve static files (stylesheets, scripts, images): app.use(path, middlewareFunction)

let staticFilesPath = __dirname + "/public";

app.use("/", express.static(staticFilesPath));

Serve JSON on a Specific Route

A REST (REpresentational State Transfer) API allows data exchange in a simple way, without the need for clients to know any detail about the server.

let dataJson = {"message": "Hello json"};

app.get("/json", (req, res) => {
  res.json(dataJson);
});

Use the .env File

The .env file is a hidden shell file that is used to pass environment variables to your application. Accessible from the app as process.env.VAR_NAME. Add variables to .env with this syntax: VAR_NAME=value

let dataJson = {"message": "Hello json"};

app.get("/json", (req, res) => {
 if (process.env.MESSAGE_STYLE === "uppercase") {
   dataJson.message = dataJson.message.toUpperCase();
 };

 res.json(dataJson);
});

Implement a Root-Level Request Logger Middleware

For every request, it should log to the console a string taking the following format: method path - ip. An example would look like this: GET /json - ::ffff:127.0.0.1.

app.use(function middleware(req, res, next) {
  console.log(req.method + " " + req.path + " - " + req.ip);
  next();
});

Chain Middleware to Create a Time Server

app.get('/now', 
(req, res, next) => {
  req.time = new Date().toString();
  next();
},  
(req, res) => {
  res.json({time: req.time})
});

Get Route Parameter Input from the Client

route_path: ‘/:word/echo’
actual_request_URL: ‘/myString/echo’
req.params: {word: ‘myString’}

app.get("/:word/echo", (req, res) => {
  res.json({"echo": req.params.word});
});

Get Query Parameter Input from the Client

route_path: ‘/name’
actual_request_URL: ‘/name?first=firstname&last=lastname’
req.query: {first: ‘firstname’, last: ‘lastname’}

app.get("/name", (req, res) => {
  res.json({name: `${req.query.first} ${req.query.last}`})
});

Use body-parser to Parse POST Requests

POST is the default method used to send client data with HTML forms. In REST convention, POST is used to send data to create new items in the database (a new user, or a new blog post).
In these kind of requests, the data doesn’t appear in the URL, it is hidden in the request body. The body is a part of the HTTP request, also called the payload.
Add "body-parser": "^1.15.2", in your package.json as dependencie to parse the body data.

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

Get Data from POST Requests

Mount a POST handler at the path /name.

app.post("/name", function(req, res) {
  res.json({name: `${req.body.first} ${req.body.last}`})
});