REST Api implementation in Firebase Functions - node.js

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);
}));

Related

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

How to set Routes for APIs

I am building an API to manage meetups with nodeJS. I have build an endpoint with the route "/meetups/:id/" to fetch a specific meetup record by its id. And then I want to fetch all the upcoming meetup records and I tried to use "/meetups/upcoming/" but when I query it, I get the not found error (404). It seems like the second route is not recognised.
Here is the code defining the two routes
the request from postman
Any help on how can I handle that?
Thanks.
Route is '/api/v1/meetups/upcoming/all'. Move res.status outside the map function.
EDIT: you'll have to change the route which has to be different from api/v1/meetups/:id. Reason is when route '/api/v1/meetups/upcoming' is requested express sees it as the same route as before and takes 'upcoming' as the parameter.
app.get("/api/v1/meetups/upcoming/all", function(req, res) {
var today = new Date();
var upcomings = db.meetups.map(function(meetup) {
if(meetup.happeningOn > today) {
return meetup;
}
});
res.status(200).send({
status: 200,
data: upcomings
});
});
You need to move the res.status piece outside of the const upcomings definition.

Express JS get Params

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.

Resources