[英]How to get the post request params in express server?
The following is the code for posting a product using an angular service.以下是使用 angular 服务发布产品的代码。 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.其他动词如
GET
, DELETE
工作正常。
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.但是
POST
动词中的参数在 express 服务器中没有收到。
In order to parse json-payloads you need an appropriate parser set up.为了解析 json-payload,您需要设置适当的解析器。 You can use express's built-in parser to do that:
您可以使用 express 的内置解析器来执行此操作:
const express = require('express');
const app = express();
app.use(express.json());
app.post("/api/products", async (req, res) => {
console.log("req :", req.body);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.