Sending response back from Node.js server to browser


App.js −

const http = require('http');
const server = http.createServer((req, res)=>{
   console.log(req.url, req.method, req. headers);
});
server.listen(3000);

As shown in above example code, we have request and response parameter object as an argument in createServer method.

Response (res) object will be used to send back data to client. It has many properties, some are explained below −

res.setHeader(‘Content-Type’, ‘text/html’); this line will set the format of response content o text/html.

How to send html content from node.js

write() function method on response object can be used to send multiple lines of html code like below.

res.write(‘<html>’);
res.write(‘<head> <title> Hello TutorialsPoint </title> </head>’);
res.write(‘ <body> Hello Tutorials Point </body>’);
res.write(‘</html>’);
//write end to mark it as stop for node js response.
res.end();
//end () is function to mark a stop for node js write function.

Once end() is written , thereafter no write is allowed on the same response object else it will result into an error in code execution

Now, we will run response code.

Complete App.js with response −

const http = require('http');
const server = http.createServer((req, res)=>{
   console.log(req.url, req.method, req. headers);
   res.write('<html>');
   res.write('<head> <title> Hello TutorialsPoint </title> </head>');
   res.write(' <body> Hello Tutorials Point </body>');
   res.write('</html>');
   //write end to mark it as stop for node js response.
   res.end();
});
server.listen(3000);

run it on terminal: node App.js

Open a browser and navigate to localhost:3000 and We will see below output on browser.

Sending response from node will be made simpler with the use of express.js in upcoming articles.

Headers are important in both http request and response. They are useful in identifying the right content type and accept type from server and client. Cache-control is one such header which determines caching mechanisms between server and client.

In single page applications, token is passed in request for authentication. Session management is also handled using http session.

Request, response security mechanisms also differs based on http method selected to transfer the data between client and server.

Updated on: 13-May-2020

751 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements