Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Create route files:
- Create a "routes" folder in the root of your project.
- Inside the "routes" folder, create a file named "products.js" for product-related routes.
- Define the routes in "products.js":
- javascript
- Copy code
- // routes/products.js
- const express = require('express');
- const router = express.Router();
- // Define routes
- router.get('/', (req, res) => {
- // Logic to handle GET request for fetching all products
- });
- router.get('/:id', (req, res) => {
- // Logic to handle GET request for fetching a specific product by ID
- });
- router.post('/', (req, res) => {
- // Logic to handle POST request for creating a new product
- });
- router.put('/:id', (req, res) => {
- // Logic to handle PUT request for updating a specific product by ID
- });
- router.delete('/:id', (req, res) => {
- // Logic to handle DELETE request for deleting a specific product by ID
- });
- // Export the router
- module.exports = router;
- Include the routes in the main Express app (app.js):
- javascript
- Copy code
- // app.js
- const express = require('express');
- const bodyParser = require('body-parser');
- const productsRoutes = require('./routes/products'); // Import the products routes
- const app = express();
- const PORT = process.env.PORT || 3000;
- app.use(bodyParser.json());
- app.use(bodyParser.urlencoded({ extended: true }));
- // Use the products routes
- app.use('/products', productsRoutes);
- // Start the server
- app.listen(PORT, () => {
- console.log(`Server is running on port ${PORT}`);
- });
- With this setup, the product-related routes defined in "products.js" will be accessible under the base URL "/products" in your Express app. For example, the route handling the GET request for fetching all products will be available at "/products/" (assuming your app is running on port 3000). Similarly, other routes will follow the "/products/:id" pattern.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement