JavaScript API Notes
At some point, this will become a very detailed turtorial...
Building an API with Node & Express.
NPM:
Some junk about the importance of NPM and package.json
App.js
To create an Express app object, all we need are the following two lines:
const express = require('express');
const app = express();
This object has several methods. Here is a list of some of the methods and what they do.
- app.listen(port)
- This tells the server to listen on a specified port and puts it in a running state. When a server is in a “running” state, it means that it can now accept requests from the Runtime Manager.
- res.sendFile(path)
- We can respond to requests with a file using the sendFile() method. This works in the background to set appropriate headers which instructs the browser on how to handle the file you want to send, based on its type. It needs an absolute file path.
- absolutePath = __dirname + relativePath/file.ext for example:
res.sendFile(__dirname + "/views/index.html")
});
Middleware:
Middleware are functions that intercept route handlers, and add some kind of information. We can use middleware to add static assets (stylesheets, images, scripts) that the application needs.
Middleware needs to be mounted using the method app.use() for example:
app.use(path, middlewareFunction)
Path is optional and when it is not passed, the middleware is executed for all requests.
Routes:
In Express, routes follow the following structure:
app.METHOD(PATH, HANDLER) for example:app.use('/api', recipeRouter);
- METHOD is an http method and it is in lowercase.
- PATH is a relative path on the server.
- HANDLER is a function that Express calls when the route is matched. Handlers take the following form:
- function(req, res) {...}
- req = the request object
- res = the response object

Thanks for stopping by 🙃️, BYE!