Shoulder.dev Logo Shoulder.dev

Creating Custom Routes in benhall/express-demo

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:

  1. Create a new file named auth.js in the routes 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;
  1. 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' });
});
  1. Import the new auth.js file in the index.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:

  1. 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"
}
  1. 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"
}
  1. User logout test:
curl -X GET http://localhost:3000/api/auth/logout

Expected response:

{
"message": "User logged out successfully"
}