Serving a Response to the Browser

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 234:- Serving a Response to the Browser

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.

28. Node.js Writing - Our First Server

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

I am not able to access videos from second class and further. I have already completed first class

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?