NodeJS and Express Note
Posted on: September 04, 2023
API
- API - Application Programming Interface
- It is a software intermediary that allows two aplications to communicate, like a messenger delivers your request to one end and delivers the response back to you
- It is like a waiter in a restaurant, takes order from customer to the kitchen (the API server) and brings the food back to the customer
- It is not a databse or web server or device, but a access point that can access them
- There are a few APIs types, e.g. Java API, API for communication between object classes, REST API
REST API
REST
- REST - REpresentational State Transfer, it defines a set of rules for communication bewtween a client and a server
- REST client - a code or app used to communicate with REST servers
- A server contains resources that the client wants to access or change
- A resource is any information that the API can return
Different components of a REST API
API client
- Responsible for handling the data returned by the API and presenting it to the user
- This can mean different things depending on context:
- a development tool that helps to explore, test, and debug APIs
- a service that uses language-specific libraries and SDKs to initiate API requests
API request
API server
API response
Serve a 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 (it can be a string, or even a regular expression). HANDLER is a function that Express calls when the route is matched. Handlers take the form function(req, res) {...}
, where req is the request object, and res is the response object.
// Handler Example:// This handler will serve the string 'Response String'.function(req, res) {res.send('Response String');}// Method Example:app.get("/", (req, res) => {res.send("Hello Express");});
Serve a HTML file
You can respond to requests with a file using the res.sendFile(path)
method. Behind the scenes, this method will set the appropriate headers to instruct your browser on how to handle the file, according to its type. Then it will read and send the file. This method needs an absolute file path.
This method requires an abosulte path, so recommend to use the Node global variable __dirname
to calculate the path.
app.get("/", (req, res) => {res.sendFile(__dirname + '/relativePath/file.text');});
Serve static assets
An HTML server usually has one or more directories for storing the static assets (stylesheets, images , scripts) needed by your application, and they can be accessed using the middleware express.static(path)
, where the path
is the absolute path of the folder containing the assets.
A middleware needs to be mounted using the method app.use(path, middlewareFunction)
. The first path argument is optional. If you don’t pass it, the middleware will be executed for all requests.
app.use("/public", express.static(__dirname + "/public"));
Serve JSON on a specific route
JSON is a convenient way to represent a JavaScript object as a string, so it can be easily transmitted around the web. Inside the route handler, use the method res.json()
, passing in an object as an argument. Behind the scenes, it converts a valid JavaScript object into a string, then sets the appropriate headers to tell your browser that you are serving JSON, and sends the data back.
app.get("/json", (req, res) => {res.json({ message: "Hello json" });});
Use the .env file
The .env file is a hidden file that is used to pass environment variables to your application and no one but only you can access it. So it can store secret data like API keys from external services or your database URI, or configuration options for changing application behaviour.
All environment variable names are uppercase and use underscore to seperate words, no quotes needed because .env
is a shell file. When assigning values, no space around "=" sign, e.g. VAR_NAME=value
. To access the varible from other parts of the app, use the global Node object process.env
, and variables are passed as strings, e.g. process.env.VAR_NAME
.
Middleware
Middleware functions are functions that take 3 arguments: the request object, the response object, and the next function in the application’s request-response cycle. It can have some side effects when executing some code. The middleware must be mounted before all the routes that depend on it.
function(req, res, next) {console.log("I'm a middleware...");next();}
To mount a middleware function at root level (i.e. apply to every request), you can use the app.use(<mware-function>)
method. Can also be used for requests like GET, DELETE, PUT, and other HTTP requests. E.g. app.post(<mware-function>)