0

This is 'product.js' file, and when ever I am calling the api '/achaar/products/1', the value of val is giving empty in console. Other api calls like '/achaar/products' is working fine, but on calling with id this is not working.

const express = require('express')
const router = express.Router();
const json_data = require('./test_data');
const cons = require('./constants')

/*
url is : /achaar/products
replace test data with database datas
*/

router.get(cons.URLS.all_product,(req,res) => {
res.json(json_data)
})

router.get(cons.URLS.all_product+'/:id',(req,res) => {
console.log(req.params.id)
var val = json_data.achaar.filter(function (x) { return x.id === req.params.id })
console.log(val)
})

module.exports = router

Here is my test_data.js file

 {
 "achaar" : [
    {
        "id" : 0,
        "name" : "Ginger Tangi",
        "cost" : 2000
    },
    {
        "id" : 1,
        "name" : "Mango Khatta",
        "cost" : 1200
    },
    {
        "id" : 2,
        "name" : "Gaas Dhari",
        "cost" : 3000
    },
    {
        "id" : 3,
        "name" : "Cream Tangy",
        "cost" : 1000
    }
 ]
}
2
  • 1
    req.params.id is a string, and you're checking using type/value equality on an integer in your data. Try converting the id to a number: Number(req.params.id) and then doing the check. Commented Oct 10, 2021 at 15:13
  • More information here. Commented Oct 10, 2021 at 15:17

1 Answer 1

1

Because you use === and it was check value and type is equal

You should convert req.params.id to number because id of data is number.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.