Scenario:
You are working on a new feature for the benhall/express-demo project, which involves user authentication. To implement this feature, you need to add new routes to the Express application to handle user registration, login, and logout functionality.
Solution:
- Create a new file named
auth.js
in theroutes
folder. This file will contain the new routes for user authentication.
const express = require('express');
const router = express.Router();
// Define routes for user authentication here
module.exports = router;
- Define the new routes in the
auth.js
file. For this example, we will create routes for user registration (/register
), login (/login
), and logout (/logout
).
router.post('/register', (req, res) => {
// Handle user registration logic here
res.status(201).json({ message: 'User registered successfully' });
});
router.post('/login', (req, res) => {
// Handle user login logic here
res.status(200).json({ token: 'JWT_TOKEN' });
});
router.get('/logout', (req, res) => {
// Handle user logout logic here
res.status(200).json({ message: 'User logged out successfully' });
});
- Import the new
auth.js
file in theindex.js
file and register the routes.
const express = require('express');
const app = express();
const auth = require('./routes/auth');
app.use('/api/auth', auth);
// ... other routes
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Tests:
To verify the new routes are working correctly, you can use a tool like Postman or curl to send requests to the endpoints. Here are some example tests:
- User registration test:
curl -X POST -H "Content-Type: application/json" -d '{"username": "testuser", "password": "testpassword"}' http://localhost:3000/api/auth/register
Expected response:
{
"message": "User registered successfully"
}
- User login test:
curl -X POST -H "Content-Type: application/json" -d '{"username": "testuser", "password": "testpassword"}' http://localhost:3000/api/auth/login
Expected response:
{
"token": "JWT_TOKEN"
}
- User logout test:
curl -X GET http://localhost:3000/api/auth/logout
Expected response:
{
"message": "User logged out successfully"
}