简体   繁体   中英

I can't fetch the product from the MongoDB using react native nodejs

I have an index file in which there is an API for fetching a product from the database with the productId. I passed a specific productId (copied and pasted from Mongo Atlas) to the postman to test the API and it worked properly and brought the product. Here is the postman test that you can see API brings the product.

Here is the front end fetching of the API

  React.useEffect(() => {
try {
  console.log(productId)
  console.log("I am in try block")
  fetch("http://10.0.2.2:3000/fetchtproduct/${ productId }")
      .then((res) => res.json())
      .then(data => {
        console.log(typeof (data))
        console.log(data);
        setData(data);
        console.log(data.name)
      })
}
catch (error) {

  console.log("couldn't fetch data from your API Sooraj!")
  console.log(error);
}}, [])

And here is the API itself

router.get('/fetchtproduct/:id', async (req, res) => {
try {
    const product = await products.findById(mongoose.Types.ObjectId(req.params.id)) //find(); 
    res.send(product)
} catch (error) {
    return res.status(442).send(error);
    console.log("Could not get product");
}})

I have already tried findOne, findById, find, JSON.strinigify() Please help me get out of this problem. I have wasted much time finding errors.

The error it shows is

Unidentified Token '<' 
JSON Parse Error

And sometimes it shows null object like this

 62fd0148877cab7bc5011753
 LOG  []
 LOG  62fd0148877cab7bc5011753
 LOG  I am in try block
 LOG  object
 LOG  {}
 LOG  62fd0148877cab7bc5011753
 LOG  {}
 LOG  undefined

Hi buddy just change double quotes in fetch into ``

Like

 try {
  console.log(productId)
  console.log("I am in try block")
  fetch(`http://10.0.2.2:3000/fetchtproduct/${productId}`)
      .then((res) => res.json())
      .then(data => {
        console.log(typeof (data))
        console.log(data);
        setData(data);
        console.log(data.name)
      })
}
catch (error) {

  console.log("couldn't fetch data from your API Sooraj!")
  console.log(error);
}}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM