Read a product API

In the backend, we will add a GET route that queries the Product collection with an ID and returns the product in the response.

mern-marketplace/server/routes/product.routes.js:

router.route('/api/products/:productId')      .get(productCtrl.read) 

The :productId param invokes the productByID controller method, which retrieves the product from the database and appends it to the request object. The product in the request object is used by the read controller method to respond to the read request.

mern-marketplace/server/controllers/product.controller.js:

const read = (req, res) => {  req.product.image = undefined  return res.json(req.product)}

In api-product.js, we will add a fetch method to use this read API in the frontend.

Get Full-Stack React Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.