Script Valley
Express.js: APIs and Middleware
Express.js FundamentalsLesson 1.2

How to create your first Express server and handle requests

require express, app.listen, port binding, req object, res object, res.send vs res.json, HTTP methods in Express

Creating an Express Server

Every Express app starts the same way: create the app, define routes, bind to a port. The req and res objects are the core of every request handler.

Minimal working server

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Server is running');
});

app.get('/json', (req, res) => {
  res.json({ status: 'ok', message: 'Hello from Express' });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Key objects:

  • req โ€” incoming request (URL, headers, body, params)

  • res โ€” outgoing response (send data back to client)

res.send() sends a string or buffer with Content-Type: text/html. res.json() serializes an object and sets Content-Type: application/json automatically โ€” always use res.json() for API responses.

app.listen() binds the server to a port. The callback fires once the server is ready. Store the port in a variable so you can change it from an environment variable later: const PORT = process.env.PORT || 3000.

Up next

Express routing โ€” defining GET, POST, PUT, DELETE routes

Sign in to track progress

How to create your first Express server and handle requests โ€” Express.js Fundamentals โ€” Express.js: APIs and Middleware โ€” Script Valley โ€” Script Valley