API 在 nodejs 中调用给出空数组

API call giving empty array in nodejs

这是 'product.js' 文件,每当我调用 api '/achaar/products/1' 时,val 的值在控制台中为空。其他 api 调用,如“/achaar/products”工作正常,但在使用 id 调用时不起作用。

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

这是我的 test_data.js 文件

 {
 "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
    }
 ]
}

因为您使用 === 并且它检查值和类型是否相等

您应该将 req.params.id 转换为数字,因为 id 的数据是数字。