If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To serve a response to the browser using Node.js, we can use the built-in http
module. The http
module provides a createServer
method that can be used to create a basic web server. Here's an example:
javascriptCopy code
const http = require('http');
const server = http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello World!');
response.end();
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, we're creating a web server using http.createServer()
. The createServer
method takes a callback function that will be called every time a new request is received. This callback function takes two parameters: request
and response
.
Inside the callback function, we're using the response
object to write a response to the browser. We're setting the response status code to 200
and the content type to text/plain
. Then we're writing the response body using the response.write()
method, and finally we're ending the response using the response.end()
method.
The listen
method is used to start the server listening on a specific port. In this example, we're starting the server on port 3000
. When the server starts listening, the callback function passed to listen
will be called, and we're just logging a message to the console in this case.
Once you have this code saved as a file, you can run it using Node.js. Open a terminal and navigate to the directory where you saved the file, then run the command node filename.js
(replace filename.js
with the name of your file). The server will start listening on port 3000
. You can test it by opening a web browser and navigating to http://localhost:3000
.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.