Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading