Request & Response
In the "Install Express" discussion, we learned how to get our server up ands running, and then start the server and check the output. Here is the server code:
- JavaScript
- const express = require('express');
- const app = express();
- const port = 3000
- app.get('/', ( req, res ) => {
- res.send('Hello World!');
- })
- app.listen( port, () => {
- console.log(`App Server is running : Listening on port ${port}`)
- })
To recap, we:
- ∴ required (imported) express : express
- ∴ created a variable to represent the express object : app
- ∴ created a variable to define the server port number : port = 3000
- ∴ we started the server : app.listen
- ∴ and the server should now be running and waiting for a response, on port = 3000.
Waiting for a response? A response from where?
This is where our last section of code comes in:
- app.get('/', ( req, res ) => {
- })
You notice this code uses two new parameters, req, and res. But what are these new parameters and what do they do?
req & res
These properties have very specific uses with our server request. req is a property that represents the incoming request, and res is a property that represents the outgoing result of that request.
In our little example, where we simply started the server, and then output "Hello World", our req was sent when we started the server. While we didn't "request" any specific data, we did send a request to the server. And if if we add a new line logging out the req:
what we would get is a massive object of all kinds of information that represents our request.
Now for the response, we used a "method" called send to output our response to the browser window. In our case, we used res.send("Hello World");
The important thing to know about the send method of the res property is that it is very versatile. We could send a string of text, a .json file, or some HTML code with text such as:
- <h6>This is My Header</h6>
and Express will process the http req and convert the output appropriately. So for these little examples, the browser window would display"
- a string of text,
- a json file contents, or
- an actual html markup for an <h6> element
Summary
To sum it all up:
- ∴ req is an object, created by express that represents the http request sent to the server.
- ∴ res represent the result of the request. There are many methods of the res property that can be found here. *note there is a quick index on the right side of the page.
- ∴ Express will convert the request into the proper type of result, based on the http request.
Back to Top