How to create a simple HTTP server in Node.js
· Category: Node.js
Short answer
Use the built-in http module to create a server with http.createServer() and listen on a port using .listen().
Steps
- Import the
httpmodule withconst http = require('http');. - Create a server using
http.createServer((req, res) => { ... }). - Inside the callback, set response headers with
res.writeHead(200, { 'Content-Type': 'text/plain' });. - Send response data with
res.end('Hello World\n');. - Start listening on a port with
server.listen(3000, () => console.log('Server running'));.
Tips
- For production, consider using a framework like Express.js or Fastify to handle routing and middleware efficiently.
- Always set appropriate Content-Type headers so browsers interpret responses correctly.
Common issues
EADDRINUSEmeans another process is already using the port. Change the port or kill the existing process.- Forgetting to call
res.end()can cause the client to hang indefinitely waiting for the response to finish.