Home > Blockchain >  Not getting the single product data from products.js while using express
Not getting the single product data from products.js while using express

Time:11-06

Here is my server.js file where the routes are created using express.

const express = require('express');
const products = require('./data/products');

const app = express();

app.get('/', (req, res) => {
  res.json('Api is running succesfully...');
});

app.get('/api/products', (req, res) => {
  res.json(products);
});

app.get('/api/product/:id', (req, res) => {
  const product = products.find((x) => x._id === req.params.id);
  res.json(product);
});

app.listen(5000, console.log('server is running at port 5000'));

So I have used following in the products.js file to export it:

module.exports = products;

The problem is i get the products data when i go to the route localhost:5000/api/products but when i go to route localhost:5000/api/product/1 i dont get anything when i console logged the req.params.id it gives the id number which i have in the route i.e 1 but when i logged product it gives me undefined. Please help me why i am not getting single product??

CodePudding user response:

Express always return a string in req.params.<VAR>, so if you are sure that you will get the Number from the params then convert the string to the number by parseInt or .

Convert All To Number

products.find((x) =>  x._id ===  req.params.id);

Convert All to String

products.find((x) => x._id.toString() === req.params.id.toString());
  • Related