0

The following is the code for posting a product using an angular service. Here I'm passing the product as the body


  addProduct(product): Observable<any> {
    return this.http.post<Observable<any>>(
      `http://localhost:4401/api/products`,
      {
        product,
      }
    );
  }


But when I try to access it inside my express server I am getting an undefined.

app.post("/api/products", async (req, res) => {
  console.log("req :", req.body);
});

Other verbs like GET, DELETE is working fine.

Also the following is also working fine:

app.get("/api/products/:id", async (req, res) => {
  try {
    const responseData = await db.get(req.query.id);

    res.json({ product: responseData  });
  } catch (e) {
    console.log(e);
  }
});

But the params inside the POST verbe is not getting received inside the express server.

mx_code
  • 2,441
  • 1
  • 12
  • 37
  • Does this answer your question? [req.body empty on posts](https://stackoverflow.com/questions/24543847/req-body-empty-on-posts) – O. Jones Dec 09 '20 at 17:15
  • Actually body parser is deprecated. I use multer. Is there an alternative? – mx_code Dec 09 '20 at 17:19

1 Answers1

2

In order to parse json-payloads you need an appropriate parser set up. You can use express's built-in parser to do that:

const express = require('express');
const app = express();
app.use(express.json());

app.post("/api/products", async (req, res) => {
  console.log("req :", req.body);
});
eol
  • 23,236
  • 5
  • 46
  • 64
  • Happy to help, please don't forget to upvote/accept my answer by clicking the checkmark on the left side. – eol Dec 09 '20 at 18:03