Build RESTful APIs easily with Node.js & Express
Definition: Express.js is a fast, unopinionated, minimalist web framework for Node.js. It simplifies building web applications and APIs.
app.get(), app.post()Install Express in your Node.js project:
npm init -y
npm install express
Use Express when your project requires:
/users, /login)Create index.js file with this code:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Root route
app.get('/', (req, res) => {
res.send('Welcome to Express.js API!');
});
// Example POST route
app.post('/user', (req, res) => {
const user = req.body;
res.json({ message: 'User created', user });
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Log every incoming request:
app.use((req, res, next) => {
console.log(\`\${req.method} request to \${req.url}\`);
next();
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});