以下是我的 Angular http put 请求
postRequest(data) : Observable<any>{
return this.http.post("http://localhost:5050",data).pipe(map(this.dataHandler));
}
当我进行此调用时,将在服务器端调用以下方法:
app.put("/",function(request,response){
response.send("Put request received successfully");
})
我想检索从客户端发送的数据,作为 express 中服务器端放置请求的一部分。 请帮忙。提前致谢。
最佳答案
首先,如果你想执行一个PUT
请求,你应该使用put
而不是post
。
this.http.put(...)
然后在你的服务器端,你可以使用body-parser
来解析请求数据,并在你的中间件上使用它
const bodyParser = require('body-parser');
/* ... */
app.use(bodyParser.json()); // If you're sending a JSON payload
app.use(bodyParser.urlencoded({ extended: true })); // application/x-www-form-urlencoded
app.use(bodyParser.text()); // You're sending text/plain
/* ... */
app.put("/",function(request, response){
console.log(request.body); // Data is inside body
response.send("Put request received successfully");
});
您需要发送:Content-Type: application/json
才能使 bodyParser.json()
正常工作,否则您的 JSON 负载将不会被解析,或 application/x-www-form-urlencoded
用于 bodyParser.urlencoded()
The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.
在您的特定情况下,您要发送 Content-Type: text/plain
所以只需使用:
app.use(bodyParser.text());
关于javascript - 如何使用客户端作为放置请求的一部分发送的 express 访问服务器端的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777545/