nodejs get req.param from route - node.js

I am trying to get the url parameter of an url request from the front in my nodejs backend.
fetch(`http://localhost:9000/sent/5768797675645657`)
Here is my app.js file :
app.use('/sent/:id', require('./routes/sent'));
And my /routes/sent.js file :
router.get('/', function(req, res) {
console.log(req.params)
})
How can I get the console.log(req.params) to work?

So, app.use accepts two parameters: the portion of the URL, and a callback function.
In order to your app works, you've to change the /routes/sent.js and make it exports the function, so it can be used when you're requiring it.
Just change it to
module.exports = function (req, res) {
console.log(req.params)
}
and you're ready to go!

Related

first portion of route url is not included

I have a route where I built two GET APIs. I would like one to redirect from /download to /zip all while passing a parameter. The problem is I am getting a 404 for some reason the routes url is not being included in the redirect()
Here are the APIs.
// respond with xml from from static folder
router.get('/zip/:id', function (req, res) {
fileName = req.params.id
});
router.get('/download', function (req, res, next) {
var id = req.query.id
res.redirect('/zip?id='+ id);
});
module.exports = router;
I get a 404 when testing the URL:
localhost:8000/rest/pluto/v1/plugin/download?id=networktool
I am thinking it might be how I have the middleware setup but not real sure. I'm still new to node/express.
You are redirecting to a route that isn't actually defined. With your /zip/:id route definition:
router.get('/zip/:id', function (req, res) {
var fileName = req.params.id
});
The way that is defined, you have to have id information in the URL itself, so while the following routes would work:
/zip/networktool
/zip/1234
these routes would not:
/zip
/zip?id=networktool
/zip?id=1234
because Express is looking for the id to be built into the route itself. So you can do one of two things. You can either change your redirect to:
router.get('/download', function (req, res, next) {
res.redirect('/zip/'+ req.query.id);
});
or, you can modify your /zip route to make the id parameter optional with ?:
router.get('/zip/:id?', function (req, res) {
var fileName = (req.params.id) ? req.params.id : req.query.id;
});
I would recommend the first option, as the latter optional parameter only makes your zip route more complicated and require extra handling of whether id is actually passed to your route.
The path /zip/:id is expecting a path parameter not a query parameter.
You should redirect like this
res.redirect('/zip/'+ id);

How to get the router values containing special characters in express router

I am working on to get route value in Nodes js using express framework
the url goes like
http://localhost:3000/course/view/turbine/turcV39/%20V42/%20V44/%20V47
Need to get the value "V39/%20V42/%20V44/%20V47" from the above url and route
router.get('/view/turbine/:turc?', function(req, res) {
console.log('a');
});
You can use regex to get it, like this
app.get(/\/view\/turbine\/turc(.*)/, function(req, res) {
console.log(req.params[0])
});

Express route with /?

I want to route 2 different requests.
/api/heroes/:id
/api/heroes/?name=
So using nodejs and express I write the server to handle this request.
To handle the first request I write below code:
app.get('/api/heroes/:id', jsonParser, function (req, res) {
To handle the second request I write as below:
app.get('/api/heroes/name', jsonParser, function (req, res) {
But only the first handle working as expected. The 2nd request is handled by:
app.get('/api/heroes', jsonParser, function (req, res) {
How do I change the code so the second handle can work?
If I correctly got your question, then probably you asking why req for /api/heroes/?name= is handled by /api/heroes.
You are trying to send query string parameter in 2nd req which will be handled by route /api/heroes. You will get query string parameter in req.query object.
So, your first request handler will work for urls - /api/heroes/:id (eg - /api/heroes/123) as follow:
app.get('/api/heroes/:id', function (req, res) {
var id = req.param.id
}
and for 2nd req: /api/heroes?name= (eg - /api/heroes?name=abc)
app.get('/api/heroes', function (req, res) {
var name = req.query.name
}
Refer here req.query
This is what is expected:
For query parameters /api/heroes/?name= is handled by
app.get('/api/heroes', jsonParser, function (req, res) {
What you can do is to check if req.query.name is undefined then act as normal or act with the query. Using if...else condition.
/api/heroes/name is the endpoint with name.
You can differentiate if you want as below:
app.get('/api/heroes/name/:text', jsonParser, function (req, res) {

In REST API, How to restrict URL access from browser using Nodejs & Expressjs

I have a MEAN stack application and using Node.js and Express.js as back-end API.
Assuming I have a 'comments' route as follow
/* GET /comments listing. */
router.get("/", function(req, res, next) {
Comment.find(function(err, comments) {
if (err) return next(err);
res.json(comments);
});
});
And use it in my server like this:
var commentsRouter = require('./routes/comments');
...
app.use('/comments', commentsRouter);
My question is: Is there a way to prevent users to access http://mrUrl/comments in browser and deny the request with probably 403 Forbidden message but at the same time JavaScript file tries to access the same URL will receive a content message (in the example should be res.json(comments);)
Also, would it be possible to enable such a restriction for all routes once, not for each.
Yes, you can use a middleware.
A middleware is a function you can pass before or after the main function you are executing (in this case, GET comments)
the order of the function location matters, what comes first - executes first, and you implement it like so:
app.use(myBrowsingRestrictionMiddlewareFunction) // Runs
app.use('/comments', commentsRouter);
app.use('/account', accountRouter);
You can also use within a route handler:
app.post('/comments', myMakeSureDataIsAlrightFunction, myMainCreateCommentFunction, myAfterStatusWasSentToClientAndIWishToMakeAnotherInternalActionMiddleware);
The properties req, res, next are passed into the function automatically.
which means, myBrowsingRestrictionMiddlewareFunction receives them and you can use them like so:
export function myBrowsingRestrictionMiddlewareFunction(req, res, next) {
if (req.headers['my-special-header']) {
// custom header exists, then call next() to pass to the next function
next();
} else {
res.sendStatus(403);
}
}
EDIT
Expanding regards to where to place the middleware in the FS structure (personal suggestion):
What I like to do is to separate the router from app.js like so:
app.js
app.use('/', mainRouter);
router.js
const router = express.Router();
router.use(middlewareForAllRoutes);
router.use('/comments', commentsRouter);
router.use(middlewareForOnlyAnyRouteBelow);
router.use('/account', accountRouter);
router.use(middlewareThatWillBeFiredLast); // To activate this, remember to call next(); on the last function handler in your route.
commentsRouter.js
const router = express.Router();
router.use(middlewareForAllRoutesONLYFORWithinAccountRoute);
route.get('/', middlewareOnlyForGETAccountRoute, getAccountFunction);
router.post('/', createAccount);

How do I remove a GET/POST router endpoint from express?

So I have defined an express endpoint like:
router.get('/hello', function(req, res) {
res.send('hello');
});
Later on in the code, I have something like:
router.get('/gosilent', function(req, res) {
// When this is called, it removes /hello endpoint
// such that any subsequent calls to /hello will return standard 404.
});
How do I make it work? I know how to bind endpoints but how do I unbind then?
I'm using Express 4.0.
Thanks!

Resources