← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 1 of 7

Creating HTTP server

http.createServer gives you a server that runs your function for every incoming request.

In this page:

  1. Creating HTTP server
Syntax
javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.end('response');
});
server.listen(port);

Creating HTTP server

createServer takes a request listener, and listen starts it on a port. Each request runs the listener with request and response objects. The example starts a server, calls it once and shuts down so it can run as a script.

Note: Port 0 asks the OS for any free port.

Example: Creating HTTP server

javascript
const http = require("http");
const server = http.createServer((req, res) => {
  res.end("Hello from Node");
});
server.listen(0, () => {
  const { port } = server.address();
  http.get({ port }, (res) => {
    let body = "";
    res.on("data", (c) => (body += c));
    res.on("end", () => { console.log("server said:", body); server.close(); });
  });
});

// Output:
// server said: Hello from Node

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting to call listen
  2. Never ending the response
  3. Port already in use errors
Chapter Summary
  • createServer takes a listener
  • listen binds a port
  • Each request calls the listener
  • Always end the response
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.