/NodeJS-Response

⚡how to send a http response (html or json) to the frontend using vanilla node js

Primary LanguageJavaScriptMIT LicenseMIT

Sending Response To The Frontend

  • res.writeHead to set any response headers.
res.writeHead(200, { "Content-Type": "text/html" });
  • res.write() to send the actual content for the response. the content should be either raw html or json data.
res.write("<h1>Welcome to vanilla node server</h1>");

or,

res.write(JSON.stringify(data));
  • res.end() to end the response.
res.end();

Send html response :

res.writeHead(200, { "Content-Type": "text/html" });
res.write("<h1>Welcome to vanilla node server</h1>");
res.end();

Send json response :

res.writeHead(200, { "Content-Type": "application/json" });
res.write(JSON.stringify(data));
res.end();