How to modify request to include new url parameter - node.js

I want to add a new url parameter to the req.params before sending the response back . I tried the below way . But it's not working
router.get('/customers', function(req, res) {
req.params.customerId = someval ;
// proceed my implementation
});
Is there any specific way to do this or is this impossible to do ?

If you want to add a parameter in the request send to the server, you just have to :
router.get('/customers/:customerId', function(req, res) {
console.log(req.params.customerId);
});
If you want to add a parameter in the request to send back, so I don't know why you want to do that, but you can perhaps do this with setting the new parameters in req and call a res.redirect on the good route, or play with the res.location function.

Related

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

Pass URL as query parameter in node js

I am trying to hit the URL http://localhost:3000/analyze/imageurl=https://www.google.com/ from my browser.
However, due to the presence of //, it does not correctly hit the URL, and gives me an error message, Cannot GET /analyze/imageurl=https://www.google.com/
If I get rid of the backquotes as follows, http://localhost:3000/analyze/imageurl=httpswww.google.com/, it does work correctly.
My backend API looks like this
app.get('/analyze/:imageurl', function (req, res) {
console.log('printing image url:' + req.params.imageurl);
}
Is there a way I can pass in the imageurl with backquotes as a query parameter?
You need to encode your URL before pass it on query string, using encodeURIComponent. For example:
var urlParam = encodeURIComponent('https://www.google.com/');
console.log(urlParam); // https%3A%2F%2Fwww.google.com%2F
var url = 'http://localhost:3000/analyze/' + urlParam;
console.log(url); // http://localhost:3000/analyze/https%3A%2F%2Fwww.google.com%2F
// Decode it in API handler
console.log(decodeURIComponent(urlParam)); // https://www.google.com/
encodeURIComponent
One approach could be to use Express' req.query in your route. It would look something like this:
// Client makes a request to server
fetch('http://localhost:3000/analyze?imageurl=https://google.com')
// You are able to receive the value of specified parameter
// from req.query.<your_parameter>
app.get('/analyze', (req, res, next) => {
res.json(req.query.imageurl)
})

Call Express router manually

Нello! I am looking to call a function which has been passed to an expressRouter.post(...) call.
This expressRouter.post(...) call is occurring in a file which I am unable to modify. The code has already been distributed to many clients and there is no procedure for me to modify their versions of the file. While I have no ability to update this file for remote clients, other developers are able to. I therefore face the issue of this POST endpoint's behaviour changing in the future.
I am also dealing with performance concerns. This POST endpoint expects req.body to be a parsed JSON object, and that JSON object can be excessively large.
My goal is to write a GET endpoint which internally activates this POST endpoint. The GET endpoint will need to call the POST endpoint with a very large JSON value, which has had URL query params inserted into it. The GET's functionality should always mirror the POST's functionality, including if the POST's functionality is updated in the future. For this reason I cannot copy/paste the POST's logic. Note also that the JSON format will never change.
I understand that the issue of calling an expressjs endpoint internally has conventionally been solved by either 1) extracting the router function into an accessible scope, or 2) generating an HTTP request to localhost.
Unfortunately in my case neither of these options are viable:
I can't move the function into an accessible scope as I can't modify the source, nor can I copy-paste the function as the original version may change
Avoiding the HTTP request is a high priority due to performance considerations. The HTTP request will require serializing+deserializing an excessively large JSON body, re-visiting a number of authentication middlewares (which require waiting for further HTTP requests + database queries to complete), etc
Here is my (contrived) POST endpoint:
expressRouter.post('/my/post/endpoint', (req, res) => {
if (!req.body.hasOwnProperty('val'))
return res.status(400).send('Missing "val"');
return res.status(200).send(`Your val: ${req.body.val}`);
});
If I make a POST request to localhost:<port>/my/post/endpoint I get the expected error or response based on whether I included "val" in the JSON body.
Now, I want to have exactly the same functionality available, but via GET, and with "val" supplied in the URL instead of in any JSON body. I have attempted the following:
expressRouter.get('/my/get/endpoint/:val', (req, res) => {
// Make it seem as if "val" occurred inside the JSON body
let fakeReq = {
body: {
val: req.params.val
}
};
// Now call the POST endpoint
// Pass the fake request, and the real response
// This should enable the POST endpoint to write data to the
// response, and it will seem like THIS endpoint wrote to the
// response.
manuallyCallExpressEndpoint(expressRouter, 'POST', '/my/post/endpoint', fakeReq, res);
});
Unfortunately I don't know how to implement manuallyCallExpressEndpoint.
Is there a solution to this problem which excludes both extracting the function into an accessible scope, and generating an HTTP request?
This seems possible, but it may make more sense to modify req and pass it, rather than create a whole new fakeReq object. The thing which enables this looks to be the router.handle(req, res, next) function. I'm not sure this is the smartest way to go about this, but it will certainly avoid the large overhead of a separate http request!
app.get('/my/get/endpoint/:val', (req, res) => {
// Modify `req`, don't create a whole new `fakeReq`
req.body = {
val: req.params.val
};
manuallyCallExpressEndpoint(app, 'POST', '/my/post/endpoint', req, res);
});
let manuallyCallExpressEndpoint = (router, method, url, req, res) => {
req.method = method;
req.url = url;
router.handle(req, res, () => {});
};
How about a simple middleware?
function checkVal(req, res, next) {
const val = req.params.val || req.body.val
if (!val) {
return res.status(400).send('Missing "val"');
}
return res.status(200).send(`Your val: ${val}`);
}
app.get('/my/get/endpoint/:val', checkVal)
app.post('/my/post/endpoint', checkVal)
This code isn't tested but gives you rough idea on how you can have the same code run in both places.
The checkVal function serves as a Express handler, with request, response and next. It checks for params first then the body.

How to write url for request with params in express?

I want to make a get request for this type of url:
http://localhost:9000/data?start-time=1234124
I want to define route in ExpressJS:
app.get("/data",function(req,res){
})
How to set parameter start-time in url?
Thanks :)
Query string parameters are contained in the req.query object. If you want to get start-time, try this:
app.get("/data", function(req, res) {
let startTime = req.query['start-time'];
});

Node/express, optional parameters switch route between get and post

I have 2 routes set up for my express server that look very close to each other. They are basically the same url, except one is post and one is get, and the get has an extra route param (which is optional). Right now these seem to work ok, however if I do not add the optional param to the get call, it thinks I'm trying to hit the post. I would like to be able to hit the get call without the passing the second optional param as well. Let me show you what I have so far:
router.param('itemID', (req, res, next, itemID) => {
verbose("itemID=", itemID);
next();
});
router.param('navigationType', (req, res, next, navigationType) => {
if (!navigationType) {
next();
}
verbose("navigationType=", navigationType);
next();
});
router.route('/:itemID/navigations')
.post(controllers.addActivity)
.all(routes.send405.bind(null, ['POST']));
router.route('/:itemID/navigations/:navigationType')
.get(controllers.listActivities)
.all(routes.send405.bind(null, ['GET']));
The routed.send405 method looks like this :
function send405(methods, req, res) {
res.set('Allow', methods.join(','));
res.status(405).json({
message: `Method '${req.method}' Not Allowed.`
});
}
So right now the issue is if I do a get on /blah123/navigations and don't add the /:navigationType variable, it thinks I am trying to hit the post method. I am very new to working with this and would appreciate any help or insight. Thanks!
When you declare a route, say GET /admins/:id, it will match any requests to GET /admins/1 or GET /admins/john. But when you do just GET /admins, it wouldn't be able to find because you haven't declared GET route matching that pattern.
To work with this, you have to specify navigationType is an optional parameter and also place the GET request first followed by the POST, like this.
router.route('/:itemID/navigations/:navigationType?')
.get(controllers.listActivities)
.all(routes.send405.bind(null, ['GET']));
router.route('/:itemID/navigations')
.post(controllers.addActivity)
.all(routes.send405.bind(null, ['POST']));

Resources