When a request reaches the server, we need a way of responding to it. In comes the router function. The router function is just a function which receives requests and routes them to any appropriate handler functions (which handle the requests) or handles the requests directly.
The router function (as well as any handler functions) always takes a request
and response
object and sends the response back to the client along with some information. You can decide what to send back in your response.
function router (request, response) {
// deal with request and sending response
}
We are now making a router function with a custom message in our response. You can write any message you want.
Add the following code to server.js
var http = require('http');
var message = 'I am so happy to be part of the Node Girls workshop!';
function router (request, response) {
}
var server = http.createServer();
server.listen(3000, function () {
console.log("Server is listening on port 3000. Ready to accept requests!");
});
We will have our router function handle requests directly for now. We want our router function to send our message in a response. To do that we will use one of the methods of response
object, which is: response.write()
. You can find more about response.write()
here
Every response has a header, which contains information about the response. We can add information to the header using response.writeHead()
. The writeHead
takes 2 parameters: status code and header object.
Add these lines to the router function
function router (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(message); //response body
response.end(); // finish response
}
The createServer() method takes a router function as an argument.
Pass your router function to createServer method
var server = http.createServer(router);
Rerun your server by typing again
node server.js
Type in your browser localhost:3000
If you see your message in the browser, congratulations you just sent your first response from the server.