By GET
Method
In View Template
Iterating a product array and send the id for detailing.
ex->(/products/123)
<% for (let product of prods) {%>
<h1 class="product__title"><%= product.title%></h1>
<a href="/products/<%=product.id%>" class="btn">Details</a>
<!--1 parsing
qury params to the route -->
<% }%>
In Routs
we need to set the routs to get dynamic content ->> use colon-> :
router.get("/products/:productId", shopController.getProduct);
/*Accessing
the get Method
Imp => Order matters paased top to
bottom
: <- can be anything
if u add a
->router.get("/products/productId"), this will not work
so more spesific ones shuld be in top
*/
In Controller
exports.getProduct = (req, res, next) => {
const proId = req.params.productId; //Extracting the value
console.log(proId + "------pro
id----------");
//Extra -> Callbacks
If you want to fetch a
product->
Product.findById(proId,
(product) => {
console.log(product);
res.redirect("/");
});
};
In Model
Now add a new callback function to model to accept an id
and return the product
static findById(id, cb) {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
}
//read
the file and get the content -> JSON.parse(fileContent)
//then
loop throuh it for find the product
const product = JSON.parse(fileContent).find((p) => p.id === id);
//send
the product
cb(product);
});
}
By POST
Method
(Most Secure way) – Parsing data through
body
In View Template
<form action="/cart" method="POST">
<button class="btn" type="submit">Add to cart</button>
<input type="hidden" name="productId" value="<%= prod.id %>"
/>
</form>
In Routs
router.post("/cart", shopController.postCart);
In Controller
exports.postCart = (req, res, next) => {
const prodId = req.body.productId; //get The product id through body
console.log(prodId);
};
By Query
Params
query params like -> admin/5?edit=true&key=value
[separated right side of ? mark]
In View Template
<a href="/admin/edit-product/<%=product.id%>?edit=true" class="btn">Edit</a>
In Routs
router.get("/admin/edit-product/:productId", adminController.getEditProduct);
In
Controller
exports.getEditProduct = (req, res, next) => {
const queryparms = req.query;
console.log(queryparms);
/*
can look for keys in query parameters
req->// http://localhost:3000/admin//edit-product/5?key=value&key2=value
query params logs ->{ key: 'value', key2:
'value' } */
const editMode = req.query.edit;
if (!editMode) {
return res.redirect("/");
}
}
Bonus->
You can use vs code debugger for debugging->
Run debugger -> select nodejs
parsing data in includes -> ejs
<%-include ('./include/add.ejs',{key:"value"}) %>

0 Comments