First Web App in Nodejs


Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, which allows JavaScript code to run on the server-side. Node.js also provides built-in modules, such as the http module, which allows you to create a server and handle HTTP requests and responses.

To create a Node.js server with HTTP, you can use the http.createServer() method, which takes a callback function that gets called every time the server receives an HTTP request

Here's an example of how to create a simple Node.js server with HTTP:

const http = require("http");
 
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
res.end(`<p>Hello World!</p>`);
});
 
server.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});
 

In this example, we first import the http module. Then we create a server using the http.createServer() method, which takes a callback function that receives two arguments: a request object and a response object.

In the callback function, we set the status code and the Content-Type header of the response to indicate that the response will be plain text. We then send the string "Hello World!" as the response body using the res.end() method.

Finally, we start the server listening on port 3000 using the server.listen() method, which takes a port number and an optional callback function that gets called when the server starts listening.

When you run this program, you can access the server by opening a web browser and navigating to http://localhost:3000. You should see the message "Hello World!" displayed in the browser.

This is a very basic example of how to create a Node.js server with HTTP. You can add more functionality to your server by using other modules or by defining your own functions and routes.