Express helps you quickly make a web server that listens to requests and sends responses. It makes building websites and APIs simple and fast.
0
0
Creating a basic Express server
Introduction
You want to create a simple website that shows pages or data.
You need a backend server to handle form submissions or user logins.
You want to build an API that other apps or websites can use.
You want to test how your frontend talks to a server locally.
You want to learn how web servers work in a friendly way.
Syntax
Express
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
express() creates the server app.
app.get(path, handler) listens for GET requests on the path.
Examples
Sends a welcome message when someone visits the home page.
Express
app.get('/', (req, res) => { res.send('Welcome to my site!'); });
Creates a new page at /about with a simple text response.
Express
app.get('/about', (req, res) => { res.send('About us page'); });
Starts the server on port 4000 instead of the default 3000.
Express
app.listen(4000, () => { console.log('Server running on port 4000'); });
Sample Program
This program creates a simple Express server. When you visit http://localhost:3000/ in your browser, it shows "Hello World!". The console logs a message to confirm the server is running.
Express
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
OutputSuccess
Important Notes
Make sure you have Node.js installed to run Express.
Run npm install express before running the server code.
Use Ctrl+C in the terminal to stop the server.
Summary
Express makes it easy to create a web server with just a few lines of code.
You define routes like app.get to respond to web requests.
Start the server with app.listen and visit it in your browser.