app.post is not documented in expressjs.com. As I understand, the server listens to a url requestion / etc. which then invokes a middleware and a callback. But all this is same in app.get.
What unique value does it provide to express?
PS. There are other questions like Express Framework app.post and app.get, or app.use and app.get (or app.post) node.js express but reading answers to the same does not provide the answer to teh question.
Edit:
The following code provides for invocation of both app.get and app.post on /login request from the browswer. Are both app.get and app.post invoked? (Presumably in the order of appearance. )
app.get('/login', function(req, res){
var username = req.user ? req.user.username : ''; res.render('login', { title: 'authenticate', username: username,
});
message: req.flash('error') });
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), function(req, res) {
res.redirect('/admin'); });
enter code here
I'd not say it's not documented, but basically it does the same as app.get() does for HTTP GET, but instead only matches HTTP POST requests.
If you don't know what the difference between a POST and a GET is, you can for example take a look here.
As for your sample code, either your get or your post handler is invoked, depending on whether the browser does a post or a get request. Both are never invoked for the same request.
Related
I have created a route to 404.html page if user enters incorrect url route
app.use(function (req, res, next) {
res.status(404).sendFile('public/404.html', {root: __dirname})
})
The problem is that when I enter existing route (in this case I use oauth google authentication) it still leads me to 404 page I created but It should redirect me to google login page.
app.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
Same with logout, it leads me to 404 page
app.get('/logout', (req, res) => {
console.log(`\n`);
console.log('\x1b[1m\x1b[31m', `*** User ${req.user.displayName} has logged out ***`);
req.session = null;
req.logout();
res.redirect('/');
});
Your 404 route needs to be the last route you declare. The declaration order matters. This way, the 404 route handler executes ONLY when no other route has already handled the request (which is what you want it to do).
In Express, routes attempt to match the incoming request in the order the route handlers are registered. Since your 404 handler matches all routes, it has to be last so that it comes into play only when no other route handler has already taken the request.
This is what I always use:
// Pages
app.get('/file', function(req, res){
res.sendFile('/path/to/file.html');
});
// 404
app.get('*', function(req, res){
res.sendFile('/path/to/404/file.html');
res.statusCode = 404;
});
Make sure the 404 handler is after all existing responses, and make sure you restart your server after updating.
So in express, we can have a chain of middleware, copies an example:
middleware = function(req, res){
res.send('GET request to homepage');
});
app.get('/', middleware, function (req, res) {
res.send('GET request to homepage');
});
What's the equivalent way to write this in koa2 please ?
I'm thinking of using it for the route, for each route i want to have a middleware to check if user is already logged in.
Thanks !
If you're simply interested in making sure a middlware runs for every route, all you have to do is register the middleware before you register your routing middelware.
app.use(middleware);
As long as you call this before you 'use' your router, it will be called for every request. Just make sure you call the next function. This is how your middleware might look like:
function middleware(ctx, next) {
// Authenticate user
// Eventually call this
return next();
}
What is the differences betwenn the 3 functions use/get/post with express?
In which case is better to use express.use instead of express.get/post?
app.use is used to load the middleware functions.
app.use example:
var myUseFunction = function (req, res, next) {
console.log('Hello World!');
next();
}
app.use(myUseFunction);
It does not have limitations for any restful api http verbs like POST, GET, PUT, PATCH, and DELETE.
app.get is route method is derived from one of the HTTP methods, and is attached to an instance of the express class.It serves the pupose of get request of apis.
GET method route
app.get('/', function (req, res) {
res.send('GET request to the page');
});
app.post is route method is derived from of the HTTP methods, and is attached to an instance of the express class. It serves the pupose of post request of apis.
POST method route
app.post('/', function (req, res) {
res.send('POST request to the page');
});
use is for middleware, e.g., all requests. It says it right in the docs:
Mounts the specified middleware function or functions at the specified path.
get is... for GET requests. post is for POST requests.
I am creating a web application based on Node.js and Express 4. I am also using Passportjs and Google OAuth 2 Startegy for authentication.
I am trying to configure my routes in order to process requests.
I have learned that this line work well:
router.get('/signin/google/callback', passport.authenticate('google', {failureRedirect: '/signin'}));
but when I decided to handle the route in the function, application stopped responding:
router.get('/signin/google/callback', function (req, res) {
passport.authenticate('google', {failureRedirect: '/signin'});
});
Do I miss something? thanks in advance
The callback of the Google OAuth function should be something like this:
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
The passport.authenticate() is middleware with arguments request,response, next. You could also define your own middlewares or the last request handler.
I'm using a passport-local strategy for authenticate users. I followed the guide given by Jared Hanson and installed connect-flash in order to give flash method to the req object. So one of my request handlers is the following:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/'
, failureRedirect: '/login'
, successFlash: 'Bienvenido'
, failureFlash: 'Credenciales no vĂ¡lidas'
})
);
When the user login fails, it redirects the user to /login again but it doesnt flash anything :/
UPDATE:
I use mongodb for session storage and I see this:
> db.sessions.find()
{ "_id" : "qZ2eiTnx6r9LR25JOz/TGhiJ", "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{\"user\":\"4ffb5b5db9cc16b615000001\"},\"flash\":{\"error\":[\"Credenciales no vĂ¡lidas\"],\"success\":[\"Bienvenido\"]}}" }
So the messages are inserted into the session object but they aren't pulled out. Should I do something special?
I assume you're pulling the messages out and rendering them in a view? Something like:
app.get('/login', function(req, res){
res.render('login', { message: req.flash('error') });
});