Return a HTML response in Node.Js application

This is not a hard thing. An easy one but many of us making problems because of not using this returning a HTML response

When we create a simple server with Node.Js it's code like this

var myServer=http.createServer(function(request,response){ 
 response.writeHead(200,{"Content-Type":"text/plain"}); 
 response.write("Hello World"); //writing a string to response
 response.end(); 
});//create server


But if we send a HTML text to display in browser ( a string like <h1>Hello World</h1> ) that text will display as it is without rendering text as HTML

We just have to do a simple change to our Node server by changing the content-type as "text/html" then the browser will render the response as  HTML.

Here is the code for simple server sending HTML responses


var myServer=http.createServer(function(request,response){
 response.writeHead(200,{"Content-Type":"text/html"});
 response.write("<h1>Hello World</h1>"); //writing a response to String
 response.end();
});//create server

No comments:

Post a Comment