Advertisement
sourav8256

Untitled

Jul 31st, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. Create route files:
  2.  
  3. Create a "routes" folder in the root of your project.
  4. Inside the "routes" folder, create a file named "products.js" for product-related routes.
  5. Define the routes in "products.js":
  6.  
  7. javascript
  8. Copy code
  9. // routes/products.js
  10. const express = require('express');
  11. const router = express.Router();
  12.  
  13. // Define routes
  14. router.get('/', (req, res) => {
  15. // Logic to handle GET request for fetching all products
  16. });
  17.  
  18. router.get('/:id', (req, res) => {
  19. // Logic to handle GET request for fetching a specific product by ID
  20. });
  21.  
  22. router.post('/', (req, res) => {
  23. // Logic to handle POST request for creating a new product
  24. });
  25.  
  26. router.put('/:id', (req, res) => {
  27. // Logic to handle PUT request for updating a specific product by ID
  28. });
  29.  
  30. router.delete('/:id', (req, res) => {
  31. // Logic to handle DELETE request for deleting a specific product by ID
  32. });
  33.  
  34. // Export the router
  35. module.exports = router;
  36. Include the routes in the main Express app (app.js):
  37. javascript
  38. Copy code
  39. // app.js
  40. const express = require('express');
  41. const bodyParser = require('body-parser');
  42. const productsRoutes = require('./routes/products'); // Import the products routes
  43.  
  44. const app = express();
  45. const PORT = process.env.PORT || 3000;
  46.  
  47. app.use(bodyParser.json());
  48. app.use(bodyParser.urlencoded({ extended: true }));
  49.  
  50. // Use the products routes
  51. app.use('/products', productsRoutes);
  52.  
  53. // Start the server
  54. app.listen(PORT, () => {
  55. console.log(`Server is running on port ${PORT}`);
  56. });
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63. 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.
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement