How to set up an Express.js server
· Category: Node.js
Short answer
Install Express with npm, require it in your entry file, create an app instance, define routes, and call app.listen() to start the server.
Steps
- Run
npm install expressin your project directory. - Create an
index.jsfile and import Express:const express = require('express');. - Initialize the app:
const app = express();. - Define a route:
app.get('/', (req, res) => res.send('Hello'));. - Start the server:
app.listen(3000, () => console.log('Server started'));.
Tips
- Use
app.use(express.json())to automatically parse JSON request bodies. - Enable environment-based port selection with
const PORT = process.env.PORT || 3000;.
Common issues
- Forgetting to send a response causes the client to timeout. Always end the request-response cycle.
- Middleware order matters; place error-handling middleware last in your application.