http.createServer
- Node.js course
- Intermediate
- Lesson 13/116
- 5 min
Learn to set up an HTTP server with http.createServer.
http.createServer
In Node.js http.createServer creates a built-in HTTP server. It comes from the http module: const http = require("http");. The server takes a handler that is called on each request.
Signature: const server = http.createServer((req, res) => { ... });. Here req represents the incoming request and res the response. Inside the handler you send a response with res.end("text"). server.listen(port) starts listening on a given port. This is the most basic way to build a web server in Node.js; frameworks like Express are built on top of it.
Handler and response
The handler takes two parameters: req (request) and res (response). req carries request details (method, URL, headers); res provides methods to write the response.
The most basic response is sent with res.end("text"). Example: const server = http.createServer((req, res) => { res.end("Hello"); });. This server replies Hello to every request. res.end both finishes the response and closes the connection; it must be called exactly once per request. When server.listen(3000) is called, the server starts listening on port 3000.
Practice Create your first server
Import the http module. Create a server with http.createServer: the handler is (req, res) => res.end("Hello"). Print "Server created" with console.log.
Starter code
// Import the http module
// write here
// Create a server with createServer
// write here
// Print "Server created"
// write hereSample solution
const http = require("http");
const server = http.createServer((req, res) => { res.end("Hello"); });
console.log("Server created");Expected output
Sunucu oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the module name
const http = require("____");
const http = require("http");
Explanation: The HTTP server comes from the http module.
2 How many parameters does the createServer handler take?
http.createServer((req, res) => { ... })- Takes no parameters
- Only one: req
- Two: req and res Correct answer
- Three: req, res and next
Explanation: The handler takes req (request) and res (response).
3 Match each piece to its role
| Term | Meaning |
|---|---|
createServer |
Creates the server |
req |
Carries the request |
res |
Lets you write the response |
listen |
Starts listening on a port |