简体   繁体   中英

How to get the post request params in express server?

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM