Passing parameters with express router correctly - javascript

import express from "express";
const router = express.Router();
router.route("/:category").get(getProductsByCategories);
router.route("/:id").get(getProductDetails);
export default router;
In this code, I've added two routes with parameters. But this code doesn't work as expected. The first route get products by categories works. But the second one doesn't. Could someone help me to troubleshoot this code, please?

The problem
From the Express documentation here
Route parameters
Route parameters are named URL segments that are used
to capture the values specified at their position in the URL. The
captured values are populated in the req.params object, with the name
of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
With that info, we can say your 2 routes are actually the same. The name of parameters doesn't make them 2 different routes. What it changes is only how the req.params object is populated. As the consequence, all the requests will go to the first route.
Suggestion
You will need to change 1 of 2 routes, for example :
To get the product by ID, you can keep it :
router.route("/:id").get(getProductDetails);
To get products by category, you can change to :
router.route("/category/:category").get(getProductsByCategories);

your route actually same route
use query string
router.route("/").get(getProduct)
and in the product function
const {id,category} = req.query
don't forget to include the keyword in url request
{{url}}/product?id=1 // to get detail
{{url}}/product?category // to get product by category

Related

Object of which I have a working method for is somehow undefined? Javascript app.patch request [duplicate]

I am trying to create two routes in my express app. One route, without a parameter will give me a list of choices, the other one with a parameter will give me the choice related to the id.
router.get('/api/choice', choice_controller.get_choices);
router.get('/api/choice/:id', choice_controller.get_choice);
When I go to .../api/choice/?id=1 the api returns the list of choices, and therefore follows the route without the param (/api/choice). How do I make sure that the router does not omit the parameter?
Thanks in advance.
UPDATE
It seems that it does not fire the /api/choice/:id route. If I remove the one without the param, it gives a 404 so. Could someone explain to me why /api/choice/?id=1 is not getting picked up by /api/choice/:id?
Basically, your declared routes are documented in the Express documentation.
The second route is resolved by a URL like /api/choice/hello where 'hello' is mapped into the req object object as:
router.get('/api/choice/:id', function (req, res) {
console.log("choice id is " + req.params.id);
});
What you are actually trying is mapping query parameters.
A URL like /api/choice/?id=1 is resolved by the first router you provided.
Query parameters are easy to get mapped against the request as:
router.get('/api/choice', function (req, res) {
console.log('id: ' + req.query.id);
//get the whole query as!
const queryStuff = JSON.stringify(req.query);
console.log(queryStuff)
});

Steam API Request Failed [duplicate]

I am trying to create two routes in my express app. One route, without a parameter will give me a list of choices, the other one with a parameter will give me the choice related to the id.
router.get('/api/choice', choice_controller.get_choices);
router.get('/api/choice/:id', choice_controller.get_choice);
When I go to .../api/choice/?id=1 the api returns the list of choices, and therefore follows the route without the param (/api/choice). How do I make sure that the router does not omit the parameter?
Thanks in advance.
UPDATE
It seems that it does not fire the /api/choice/:id route. If I remove the one without the param, it gives a 404 so. Could someone explain to me why /api/choice/?id=1 is not getting picked up by /api/choice/:id?
Basically, your declared routes are documented in the Express documentation.
The second route is resolved by a URL like /api/choice/hello where 'hello' is mapped into the req object object as:
router.get('/api/choice/:id', function (req, res) {
console.log("choice id is " + req.params.id);
});
What you are actually trying is mapping query parameters.
A URL like /api/choice/?id=1 is resolved by the first router you provided.
Query parameters are easy to get mapped against the request as:
router.get('/api/choice', function (req, res) {
console.log('id: ' + req.query.id);
//get the whole query as!
const queryStuff = JSON.stringify(req.query);
console.log(queryStuff)
});

Express JS url parameter variable issue

I have this user route
const express = require('express');
const router = express.Router();
const {
GetAll,
} = require('../areas/directory/controllers/usercontroller');
router.route('/getall?:username&:email').get(GetAll);
module.exports = router;
When I try to access the url in Postman like this: http://localhost:5000/api/user/getall?username=nameone&email=emailone
I get this error: Cannot GET /api/user/getall
But, if I change it to
router.route('/getall/:username&:email').get(GetAll);
and access the url in Postman like this: http://localhost:5000/api/user/getall/username=nameone&email=emailone
it works.
On the other hand, even if it works, I am unable to get the value of my variable.
var username = req.params.username;
will return username=nameone instead.
For http://localhost:5000/api/user/getall?username=nameone&email=emailone to work, you should change
router.route('/getall?:username&:email').get(GetAll);
to
"router.route('/getall').get(GetAll);"
and use req.query.username to access the value of username query parameter and req.query.email to access the value of email query parameter.
After making these changes, you can call http://localhost:5000/api/user/getall?username=nameone&email=emailone in Postman, you will be able to see the value of username and email in your code.
This is because you need not have to specify the query parameters in the path, like ?:username in router.route('getall').
Edit: adding few more details about path and query
Please see the top 2 solutions for this question to learn more about path and query and why you should change your code to the way I mentioned above : here is the link.
Reason for the error...
Actually the thing what you are trying to do is called query passing in the rest api..
But you are trying to access them like params
sollution 💖
follow the steps to access the queries
**To pass the data using ? in the api request should be like this you can have multiple query objects
http://localhost:5000/getall?email='email'&&password='password'
Access the query in express app like this
app.post('/getall', (req, res) => {
const {
email,
password
} = req.query
return res.status(200).json({
email,
password
})
})
The req.query contains the data you trying to pass throw ? and then query properties
Response of above code would be like this
{
"email": "'email'",
"password": "'password'"
}
You should not give query parameters in URL. So, for express the url must be just /getall and in your code you access those variables using req.params.whatever_query_parameter

Next.js: getStaticPaths for dynamic route with catching all routes [[...slug]].js

I read the docs of dynamic routes but they didn't explain much about how dynamic routes will work with "catching all routes".
My folder structure for this route is:
└──pages
└──catalog
└──[[...slug]].js
Here's my code:
export default function Catalog(props) {
return (
<Product product={props.product} />
)
}
export async function getStaticProps({ params }) {
const productSlug = params.slug[params.slug.length-1];
const data = await getSingleProduct(productSlug)
return {
props: {
product: data.product,
},
revalidate: 30
}
}
My API is WP and I have product pages URI like this /catalog/category/sub-category/product/
So if I go to the URL /catalog/category/sub-category/product/ it works fine with the code I shared below because I have const productSlug = params.slug[params.slug.length-1]; which will get my slug which I can pass to the API and use the product data just fine.
But I want to work with categories too, so if I go to /catalog/category/sub-category/ it should load the category page, and if I go to /catalog/category/ it should load up that category page.
Even this will work with the code I have because I'm getting the last element of params array which is the product slug, but that's NOT always the case. Sometimes the product is without any sub-category so the URI would be /catalog/category/product which means I can't fix it to the third element of the array and use the other two as category slugs.
The params gives me an array without any key or anything and I can't seem to figure out how to achieve this in next.js
Any help is appreciated!

Firebase Functions Express : How to get URL params with paths

I have a url in the form www.a.com/users/uid, I want to get uid.
Assume a function :
exports.smartlink = functions.https.onRequest((req, res) =>
Doing req.params returns an empty array, whereas req.query.uid when the url contains query strings works.
If your URL is "www.a.com/users/uid", "uid" will be part of req.path. You can split that on '/' to get the uid as the last element of the array returned by split.
You can only use req.params with Cloud Functions for Firebase when you're exporting an entire Express app that defines a router that uses a placeholder for the element in the path you want to extract.
Alternatively, you can use express in firebase. and use req.param to get the value.

Categories