Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jeffrey Holcomb
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jeffrey Holcomb
Full Stack JavaScript Techdegree Graduate 17,506 Points

Why can't I use app.post()?

Hello,

For this block of code which handles the value submitted via the form:

app.use((req, res, next) => {
  const num = parseFloat(req.body.number);
  const result = num * 2;
  req.doubled = result;
  next();
});

When I change it to app.post() instead, the code does not work. I guess I am having trouble understanding why app.use() works and app.post() doesn't, since after all, this block of middleware is only meant to handle the post request from the form.

Thank you.

1 Answer

Blake Larson
Blake Larson
13,014 Points

This middleware will be used before the post route. I cant see the rest of you code but I'm guessing it will be something like..

Middlewares.js

module.exports = {
    formNumDouble: function(req, res, next){
     const num = parseFloat(req.body.number);
     const result = num * 2;
     req.doubled = result;
     next();
 }
}
});

Server.js

const { formNumDouble } = require("./middlewares");

app.post('/handleForm', formNumDouble, (req, res) => { // <-- Middleware used so now req.doubled is available 
  //post action code
})

This example doesn't have any use because it's easy to just double the number on the frontend or in the post route, but there will be times where you want to authenticate a user with tokens before accessing a route and that can be very useful.