ExpressJS / NodeJS routing traffic to the base URL instead of root? - node.js

I have a route defined as:
router.get('/console/:labID?', (req, res, next) => {
When this route gets called, all additional requests are appended to /console to give you a request similar to :
/console/<new request>
I'm assuming this is intended functionality and I need to reset the route somewhere based on the request? Occasionally I will want to append it but where do I control this behavior?

Related

Is all communication from frontend to backend done via routes?

I'm working on a vuejs/express fullstack web app, and I know you can specify endpoints on the server like:
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
Which you can then hit from the client to display the home page.
But I'm wondering what about when you don't need to go to a 'route'? For example, you just want to send some data from client to server to do some calculations and then send data back to the client - do you still specify an endpoint e.g /FunctionName and access it from the frontend in the same way or is there some other way to call a function in the backend?
This is the 'express' way to define endpoints (or routes), regardless if it will return an html page like the example you've specified, or do some computation by calling other functions with user-specified parameters.
As a basic example:
app.post('/myendpoint', function (req, res) {
returnValues = callMyFunction(req)
res.send(returnValues)
})

nodejs express wildcard route not working

I'm doing an API in nodejs with express as router.
Now i'm trying to implement an client-id and an apikey to add some security to the API, and the problem that i'm facing is the next:
One of my API call is like this:
router.get("roles/get-objects/:mail/:filter*?")
So this means, that i can request an object like this:
/roles/get-objects/mail#mail.com/customer
Now the tricky part begins... when I needed to stablish a middleware to read an client-id and an apikey to verify that the client is authorized to se the API, so I did this:
In the declaration of the middleware, I use this wildcard:
router.all('/*', function (req, res, next) {
XXXX})
The thing is, I have tried in the middleware, as a wildcard everything...
I want that any API call is filtered thru that middleware, but apparently I can't find the right wildcard for it...
When I use /roles/* as wildcard, if I do a request to /roles it does work, but when I use the complete URL like: /roles/get-objects/mail#mail.com/customer it doesn't go thru my middleware.
So anybody has any idea? i'm starting to loose my mind
Thank you so much to all of you!
EDIT:
Now i'm using this middleware declaration:
router.use(function (req, res, next) {XXXX})
So when I call:
/roles/get-objects/
It's executed, the problem is when I add the email to the route:
/roles/get-objects/mail#mail.com
The app goes directly to the route that i have for that, but omits my middleware:
router.get("roles/get-objects/:mail",
I don't understand why is this happening, apparently everything should go thru my middleware first, or am I wrong?
If you want to establish a middleware to check all HTTP request whose URL starting with /roles/, the middleware should be placed before any other specific router definition:
router.use('/roles', function(req, res, next) {...});
...
router.get('/roles/get-objects/:mail', ...);
If the middleware is defined after specific route, when HTTP request comes in, the specific route is targeted and processed, the middleware won't be executed any more:
router.get('/roles/get-objects/:mail', ...);
...
router.use('/roles', function(req, res, next) {...}); // This middleware logic won't execute when request is sent to '/roles/get-objects/some-email', as the request has already been handled and response is already sent to browser.

How to use authenticated middleware properly in nodejs

I just started working on node using express framework.
app.use('/', auth, users);
and this is my route file
router.get('/' , function(req, res, next) {
render("dashboard");
});
router.get('/first' , function(req, res, next) {
//first request
});
router.get('/second' , function(req, res, next) {
//second request
});
so on...
My question is, when i pass middleware it checks for every request whether its authenticated or not using passportjs, but suppose i have a dashboard and i am sending 10 ajax requests to grab data for the widgets. So only for dashboard it will call deserialize function 11 times ,first to render the page and then for 10 ajax request. I read answer given over here,
How to properly use Passport.js?
But is it fine to go with this approach?
Yes, it is fine to go with this approach if you don't want to have security issues. You have to check the user for every request, it is very simple someone to check the network tab in the browser debugger, understand what's going on and then start spoofing your requests. You can't sacrifice security for performance because you want to execute few query less.

Expose routes on different domains

I am struggling with something that doesn't look that hard : let's say I have 2 urls to access my server :
http://localhost:80/
and an external url
http://domain.com/internal/
Is there a way to do add a basepath internal if the forwarded host is equal to the external url host?
Something like :
app.use(function(req, res, next) {
if (req.headers['x-forwarded-host'] === 'domain.com') {
app.use('/internal', routes);
} else {
next();
}
})
There wont be any direct method as in a shortcut to work your way around for personal use cases.
I suggest this simple method though. Let's take example of app.get('/xyz') route.
This can be accessed locally via http://locahost:80/xyz or yourdomain.com/xyz via any application not hosted locally (Unless you make a call using your domainname in your own application).
Add a header element with every request when the call is internal.
Now, whenever our/xyz route is called check for that header element using a if condition and if the request is made internally you'll have that header element there and then you can simply use either res.redirect or any other method that you find useful (Exporting function in current route or anything else you find easy and needful).

What does the first string parameter of app.post do?

I saw an example of app.post() function. What does the '/' mean? Are we required to use post and get methods in conjunction or can we just use one method?
app.post('/', function(req, res){
return;
});
The '/' is the root directory of your website. So that function would handle post requests for foobar.com/ . You don't have to use post and get methods in conjunction. Normally I use get and only use post for routes that I want to receive post data.
The code you posted means you're setting up the server to "listen" to the root url and execute the callback when the browser hits that url.
So, assuming you're using port 80, your url would be: http://localhost:80/
Since you're using the post method, then the callback will be executed when a post request is received on that url.
If you were to instead, use the get method, then you could just navigate to that url writing it on your browser address bar.
That way you can set all the endpoints for your web app.
Edit
If you want to know when to use post, get, and the other methods, you might want to check out this answer: Understanding REST: Verbs, error codes, and authentication
when you call app.post or app.get, you are listening for post or get requests, respectively. The first argument to these calls is the route at which you are listening for the request. so in the code below:
app.post('/', function (req,res) {
res.send("hello");
}
you are telling the server to call that function when someone makes a post request to the root of your domain (mydomain.com/).
likewise, the code below would tell the server to listen for get requests at "/getroute" (mydomain.com/getroute).
app.get('/getroute', function (req, res) {
res.send('hello');
}
post requests and get requests can be used seperately and do not have to be used in conjunction on the same route.
Look, the first parameter of app.post() is the route at which post data is received, which is sent by HTML form(action = '/') mean action attribute of your form tag, it is the route at which your HTML form will send your data. So, it no connection with the app.get parameter.

Resources