Trying to use body-parser in POST challenge

What’s happening:

I have this code:

const express = require("express");
const app = express();
const homePath = `${__dirname}/views/index.html`;
const assetsPath = `${__dirname}/public/`;
const bodyParser = require("body-parser");
require("dotenv").config();

app.use((req, res, next) => {
  const str = `${req.method} ${req.path} - ${req.ip}`;
  console.log(str);
  next();
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.route("/name").get((req, res) => {
  const { first, last } = req.query;
  const name = `${first} ${last}`;
  res.json({name: name});
}).post((req, res) => {
  res.json({ name: req.body });
});

app.use("/public", express.static(assetsPath));

app.get("/now", (req, res, next) => {
  req.time = new Date();
  req.time += 20000;
  req.time = req.time.toString();
  next()
}, (req, res) => {
  res.json({time: req.time});
});

app.get("/", (req, res) => res.sendFile(homePath));

app.get("/json", (req, res) => {
  const message = "Hello json";
  const messageUpper = message.toUpperCase();

  if (process.env.MESSAGE_STYLE === "uppercase") {
    res.json({"message": messageUpper});
  } else {
    res.json({"message": message});
  }
});

app.get("/:word/echo", (req, res) => {
  const word = req.params.word;
  res.json({echo: word});
});

But when I try to submit I get this:

The 'body-parser' middleware should be mounted

But it’s mounted already. Though since I also don’t know how to actually send a POST request, I also don’t how to test it myself with my name in the query string.

My project link(s)

solution: https://boilerplate-express.dragonosman.repl.co

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74.

Challenge: Use body-parser to Parse POST Requests

Link to the challenge:

Link to REPL:
Repl.it - boilerplate-express

Try to put that bodyParser middlewares as first.

Only the /name route needs it, right? Does it still have to be first?

Tests may check if it is the first middleware (I’m too lazy to look at the source code of the tests right now).

Putting the middlewares and the /name route first in the code did it. I still don’t get it though, since I keep reading that the middleware only needs to be above the route that needs it.

If the tests’ code requires it to be first, then that makes sense.

1 Like

Yep, many of the tests in " APIs and Microservices" section are poorly written, i.e. they test implementation not behavior.

1 Like