Lesson 13 of 30
Creating a Server
43% complete
Chapters
Chapter 13
Creating a Server
Learn how to build a basic web server using Node.js.
Theory
A Node.js server listens for incoming HTTP requests.
The basic steps are:
1. Import the http module
2. Create a server
3. Handle requests
4. Send responses
5. Start listening on a port
The request object contains information about the incoming request.
The response object is used to send data back to the client.
Example
Node.js Example
const http = require("http");
const server = http.createServer(
(req, res) => {
res.statusCode = 200;
res.setHeader(
"Content-Type",
"text/plain"
);
res.end("Welcome to Node.js");
}
);
server.listen(3000, () => {
console.log("Server started");
});Output
A Node.js server starts and responds to browser requests.
Practice
Build a server with separate responses for /, /about, and /contact.
Interview Questions
1.
How do you create a Node.js server?
2.
What are req and res?
3.
What is a port?
Quick Quiz
Which option best matches this chapter?
A.http.createServer()
B.fs.createServer()
C.path.createServer()
D.os.createServer()
Answer: http.createServer()