Express JS get Params - node.js

Who can I get parameters? If I have a get URL in expressjs like this
http://localhost:3000/api/verify-password-reset?auth_token=a944d6141&user_email=example#gmail.com
I got the first value auth_token using req.params
router.get('/verify-password-reset', (req, res) => {
console.log(req.query.auth_token);
console.log(req.query.email);
}
But email is undefined.
How can I get the email if it has a & in the URL? I tried using docs but couldn't find any solutions.

If you mean params the url looks like this for example: '/example/:id' which id is the the parameter that you specify and you can get its value like this: req.params.id
In your case you are using a QueryString, so you should use this: req.query.user_email which user_email is your key in the url.

Related

REST Api implementation in Firebase Functions

I am currently implementing Rest API standards in firebase functions. I am searching for an option for passing id as params. But I am not sure where my current Implementation was sufficient to change like that.
My code looks like this.
export const user = functions.https.onRequest(userModule);
and the URL will be like
https://firebaseapp<baseurl>/user
I need to pass the user id in the URL(not as query param)
expected URL
https://firebaseapp<baseurl>/user/{userId}
Is there any way to make the URL look like the above in firebase functions?
You can use Request object from Express to access the path parameters using params property as shown below:
app.get("/user/:userId", (req, res) => {
console.log("Path params", req.params); // { userId: "USER_ID" }
res.json(req.params);
}));

NodeJS/ExpressJS : Access URL of the post request

In a project I'm working on, I need to access the parameters of the url in the backend.
I tried this based on what I found on the internet, but it doesnt seem to work.
//url = "/getDocs?num=15"
router.get("/getDocs", function(req,res,next){
console.log(req.body.num);
res.redirect("/documents");
}
Please help
In url it seems you are using query string which can be accessed as: request.query.num
If you are passing only params in url like getDocs/:num value then it can be accessed as: request.params.num
Simple way of doing this is querying the req object with the property name:
router.get("/getDocs", function(req,res,next){
const name = req.query.name;
res.redirect("/documents");
}
If you sending as a part of route, you can use this:
router.get("/getDocs/:id", function(req,res,next){
const id = req.params.id;
res.redirect("/documents");
}
For more details check here.

Get user by query string in Nodejs

I'm trying to get user by id or by some parameters but the response always be all the users. I use the get method without any query just the test api without any authentication.
code :
router.get('/:id', async (req, res) => {
const user = await User.findById(req.query.id);
if (!user)
return res.status(404).send("The user with the given ID was not found.");
res.send(user);
});
url: http://localhost:4000/api/user?id=5e6e8159fd64bf27042a8838
the response always get all user
any help plz
#main.c is right. What you want to do is req.params.id,
req,query is used when you need to extract query properties like
/:id?sort=asc&discount=50
Then you can do req.query.sort or req.query.discount
What I can understand from your code is your route looks like router.get('/:id').
This means the URL should be something like /user/{id}.
The URL you are firing which is /user?id={id} might not be hitting this route as it does not have {id} route param in it.
The actual URL that'd hit this route is -
http://localhost:4000/api/user/5e6e8159fd64bf27042a8838.
And the way you should read id is request.params.id
I suspect /user route is pointing to get all users API which is why you are getting all users in response.

What to do when NodeJS rest api is sendind status 404 while using parameters?

I am having a strange problem while writing my api. I am using Nodejs and express. The problem occurs when i try to use GET with parameters.
This is my routes code
router.get('/addFriends/:email', (req, res, next) =>{
const email = req.params.email;
UserSchema.find({email: email}, { "friendsPending.emailSender": 1, _id : 0}, (err, data) =>{
if(err){
res.status(404).send(err);
}else{
res.status(200).send(data[0]);
}
});
});
This is my call in Postman : /users/addFriends?email=a
When running this call, server returns 404 status. It happened even when i tested it with another get call.Any comments are appriciated, however other POST and GET calls work normally (they use body not parameters). Thanks
You mixed query params and url params. To make your example working, you need to use /addFriends/my-email#gmail.com instead of /users/addFriends?email=a.
If you need to send emails via query params (everything after ?) use req.query in your controller instead of req.params.email.
This route definition:
router.get('/addFriends/:email', ...);
expects a URL that looks like this:
/addFriends/someEmail
And, you would use req.params.email to refer to the "someEmail" value in the URL path.
Not what you are trying to use:
/addFriends?email=a
If you want to use a URL such as (a URL with a query parameter):
/addFriends?email=a
Then, you would have a route definition like this:
router.get('/addFriends', ...);
And, then you would refer to req.query.email in the route handler. Query parameters (things after the ? in the URL) come from the req.query object.
In Express, route definitions match the path of the URL, not the query parameters.
when you use /addFriends/:param you force the router to match any request tha have a part in path as :param.For example:
/users/addFriends/toFavorates // will **match**
/users/addFriends/toFavorates?email=a // will **match**
/users/addFriends?email=a // will **not** match
if you want to make :param as optional part of url path put a ? after it
/addFriends/:param?
it will tell express route that :param is an optinal part. See this question
express uses path-to-regexp for matching the route paths. read the documentation for more options

Append parameters to URL

How can we append the parameters to path URL using axios.get() in react client?
axios.get('/api/order/user/', {
params: {
user_id: 2
}
})
the route defined in the express server is this.
router.route('/user/:user_id').get(//);
This is what return from the above axios.get() code.
GET /api/order/user/?user_id=2
What I want to achieve is something like this.
GET /api/order/user/2
How can this be achieved?
What you want to achieve is path parameter
const url = '/api/order/user/' + user_id;
axios.get(url);
The params property in axios is Query parameter
GET /api/order/user/?user_id=2

Resources