Could Someone Explain This body-parser Challenge:
Hi! I’m a little confused as to about this body-parser challenge. As I understand, we are supposed to be dealing with POST
requests and yet I seem to be able to pass the tests without a POST
handler.
My initial solution included a chained method:
app.route(path).get(handler).post(handler
as suggested in the previous challenge:
// Note: In the following exercise you are going to receive data from a POST request, at the same /name route path. If you want, you can use the method app.route(path).get(handler).post(handler). This syntax allows you to chain different verb handlers on the same path route. You can save a bit of typing, and have cleaner code.
However, while the solution passed the tests, I couldn’t seem to get anything out of the final .post(handler)
including console.logs
So, I presumed that for whatever reason, that post(handler)
wasn’t running, and indeed, when I removed it from the chain, the solution still passed the tests.
If some could explain what I’m missing here, I would be most grateful. I hate not understanding!!!
Is it simply because the .use(handler)
deals with all restful verbs?
Thanks in advance.
Your code so far
let express = require("express");
let bodyParser = require("body-parser");
let app = express();
console.log("Hello World");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.route("/name").get(function (req, res) {
res.json({
name: `${req.query.first} ${req.query.last}`,
});
})
// You see, I can comment out this next section of code and it still passes the tests:
.post(function (req, res) {
console.log(req.body.first, req.body.last);
res.json({
name: `${req.body.first} ${req.body.last}`,
});
});
module.exports = app;
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0
Challenge Information:
Basic Node and Express - Use body-parser to Parse POST Requests