How to Create HTTP Server in Node.js: Simple Guide
To create an HTTP server in Node.js, use the built-in
http module and call http.createServer() with a request handler function. Then, call server.listen(port) to start the server listening on a specific port.Syntax
The basic syntax to create an HTTP server in Node.js involves importing the http module, creating a server with a callback function to handle requests and responses, and then starting the server to listen on a port.
http.createServer(requestListener): Creates the server whererequestListeneris a function withrequestandresponseparameters.server.listen(port, callback): Starts the server on the givenport. The optionalcallbackruns when the server is ready.
javascript
const http = require('http'); const server = http.createServer((req, res) => { // handle request and response here }); server.listen(3000, () => { console.log('Server is running on port 3000'); });
Example
This example creates a simple HTTP server that responds with "Hello, world!" to every request. It listens on port 3000 and logs a message when ready.
javascript
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; // HTTP status code 200 means OK res.setHeader('Content-Type', 'text/plain'); res.end('Hello, world!'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Output
Server running at http://localhost:3000/
Common Pitfalls
Common mistakes when creating an HTTP server in Node.js include:
- Not calling
res.end(), which leaves the response hanging and the client waiting forever. - Forgetting to set the
Content-Typeheader, which can cause browsers to misinterpret the response. - Trying to listen on a port already in use, which causes an error.
- Not handling errors on the server, which can crash the app.
Always ensure you end the response and handle errors gracefully.
javascript
/* Wrong: Missing res.end() */ const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.write('Hello'); // Missing res.end() here causes the client to wait forever }); server.listen(3000); /* Right: Always call res.end() */ const serverFixed = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello'); }); serverFixed.listen(3001);
Quick Reference
Remember these key points when creating an HTTP server in Node.js:
- Use
http.createServer()with a request handler. - Always call
res.end()to finish the response. - Set appropriate headers like
Content-Type. - Listen on an available port with
server.listen(port). - Handle errors to keep the server stable.
Key Takeaways
Use the built-in http module and createServer() to make an HTTP server.
Always end the response with res.end() to avoid hanging requests.
Set the Content-Type header to tell the client what data is sent.
Listen on a free port and handle errors to keep your server running.
Test your server by visiting http://localhost:port in a browser.