How to use get and post both in app.use middleware - javascript

I wish to know how can I have both get and post request handled by app.use the way I do it using app.route
app.use('/', (req, res, next) => {
if (isLaunched) {
return next()
}
// You can also render if you want
res.render('coming-soon')
});
How can I handle a post request to this?

According to https://expressjs.com/en/guide/using-middleware.html the syntax you already have is used for any type of HTTP request - including GET and POST. You can detect the method via req.method.

app.use() already handles ALL http methods, including GET and POST. You can see exactly which method it is for any given request by checking req.method.
If you had trouble with some GET or POST when doing this, then please show the specific code and the specific request that it didn't work for. If you didn't try it yet, then just try it as it should work just fine.

Middlewares are mounted using app.use(<middleware-name>) so, you can add it to all routes like you do for bodyParser/CORS etc.
If you want to mount for specific routes you can use
app.post("/example" , middleware, (req,res)=>{
res.send("Hello world")
})
Refer to Use middleware on specific routes

Related

GET vs HEAD methods in Express. EXAMPLE

How to implement HEAD method in Node.js with Express server-side for a given GET method?
Can someone provide an example of usage of HEAD mehod vs GET method?
I mean code like:
Index.js
app.get ("/root", function (req, res) {
//some code
})
app.head ("/root", function (req, res) {
//some code
})
Http Head request is only used to request HTTP headers from the server and server must not return a body in it.
app.head("/root",(req,res)=>{
res.set('x-user', 'abcd')
})
Http get request is only used to get some request some body and additional headers(if needed)
app.get("/root",(req,res)=>{
res.json({email:'test'})
})
Please note: Both the type of request should not change the state in the system. For changing the state use POST, PUT, PATCH or DELETE methods

Specifying specific path with Express

I'm having trouble getting my .get() to work. My understanding of .use() vs .get() is that .use() is used for paths we want to apply things to, while .get() is more specific (choosing specific urls to apply to)
In my example, I want to show 'Applies to all pages' to any page number, but if I type in '/28', I want the .get message to show up instead. Right now, I get the .use message even when I go to /28.
router.use('/:id', function(req, res){
console.log("Things " + Date.now());
res.send('Applies to all pages ' + req.params.id);
});
router.get('/28', function(req, res){
res.send('Secret 28 page');
});
The use method is used to employ all the http verb to certain path from your express app or express router. You have to consider the precedence while using use. Here, what is happening is that you have already employed use in your dynamic router as router.use('/:id', ...) which will take get request as well.
You can employ the get router first, so that it only take getrequest in /28 and transfer all the unhandled request to other path.
router.get('/28', function(req, res){
res.send('Secret 28 page');
});
router.use('/:id', function(req, res){
console.log("Things " + Date.now());
res.send('Applies to all pages ' + req.params.id);
});
From the docs:
The order in which you define middleware with router.use() is very important. They are invoked sequentially, thus the order defines middleware precedence.
In your example your '/:id' will take precedence when matching.
So swap the order to fix your example, and in general, define more specific handlers first.
Try switching the order of your .get and use.
ExpressJS goes in sequential order when executing. Read this post for more clarification:
https://derickbailey.com/2016/05/09/in-what-order-does-my-express-js-middleware-execute/
Also, a little unrelated but you can use the .get middleware first, and pass the next step using a third parameter to your callback which is next(), if you haven't known that already.
.use() applies to all the paths regardless of HTTP verb, so in your case it applies to GET, POST, PUT and all the other requests that start with /:id path and app.get("/28") is such a request

Conflicts between endpoints in Node.js with express application

First of all, i have searched the solution to this problem and i didn't found anything. Sorry if it's duplicated.
I have in my express+node.js app two endpoints like this:
// Gets a tweet by unique id
app.get('/tweets:id', function(req, res, next) {
// Response management
});
// Gets mentions of user unique id
app.get('/tweets/mentions', function(req, res, next) {
// Response management
});
The problem is that requesting a GET petition to "/tweets/mentions", is attended first by "/tweets/:id" and later by "/tweets/mentions", making a conflict.
I have tried to change the declaration order of the endpoints, but always the request is attended by both endpoints.
Also I have tried things like "/tweets::mentions", but I need to access the endpoint via "/tweets/mentions", and I suppose there is a possible way.
How can i resolve this conflict?
Thanks.
Are you using next() in one of the handlers?
next() passes control to the next matching route, so in your example, if one of them is called and inside it you call next(), the other one will be called.
I allways recommend to use 'Router' if you have more than one base path because it helps you to keep it organized.
You can resolve the conflict by checking the value of req.params.id in the "tweet by id" handler.
For routes with additional parameters is always recommended to not use the same base path of other routes.
Something like could work for you:
app.get('/tweets/users/:id', function(req, res, next) {
// Response management
});
// Gets mentions of user unique id
app.get('/tweets/mentions', function(req, res, next) {
// Response management
});

Multiple routes in node.js and URL endpoints

app.use('/api', require('./api'));
app.use('/', require('./cms'));
The first route is for my public api, the second is the cms dashboard. But this will not work, because localhost:80/api will still load the second route too.
How to solve this? I know I can do app.use('/cms', require('./cms')); but the route would be localhost:80/cms/blog which is not fine for me.
I think the function you pass to the app.use has 3 parameters, the third one being next() callback, which calls the next middleware.
If you define your function as below, and don't call next, then it shouldn't trigger the next middleware( route too perhaps ).
app.use('/api', function(req, res, next) {
require('./api');
});
Whatever your require'd file contains, it probably receives the "next" function as its parameter. Dont call it.
update: Also, in your middleware , call res.end() to quit other routes
What's in your ./cms file? It might be that the server isn't closing the response, so it continues on to the next route.

Cookie not reading or setting properly

So I have a route in my Express app with two middleware in them:
app.foo('/thisRoute', fancyMiddleware.one, fancyMiddleware.two);
Both middlwares function in order just fine. However, in fancyMiddleware.one I have this:
var one = function(req, res, next) {
...
...
res.cookie('myCookie', data, {maxAge: 3600000});
console.log(req.cookies.myCookie)
return next();
}
To test everything I'm using PostMan to test all my requests.
The logged output for req.cookies.myCookie always returns undefined. But in the Body tab I can see that the cookie is present.
If I log out the same cookie in fancyMiddleware.two its also undefined.
why is this returning undefined?
EDIT: So, with a few answers of "why" being given, I now realize I should have also asked:
How do I read the cookie I just set?
I dont really need it right after I set it in fancyMiddleware.one, but I do need it in fancyMiddleware.two
EDIT 2: I forgot to mention I'm working with an Express 3 setup. Probably relevant.
The req.cookies is populated only once, when the cookie parser middleware is executed.
res.cookie() immediately sets the Set-Cookie header, so you'll have to use res.get('Set-Cookie') to see the current values.
You are setting the cookie on the response-object res, but you are asking it from the request req.

Categories