如何使用客户端作为put请求

时间:2018-06-09 18:57:48

标签: javascript node.js angular express

以下是我的角度http放置请求

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

我想检索从客户端发送的数据,作为快递服务器端的put请求的一部分。 请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:1)

首先,如果您要执行put请求,则应使用post代替PUT

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()

  

bodyParser对象公开了各种工厂来创建中间件。   所有中间件都将使用解析的方法填充req.body属性   当Content-Type请求标头与type选项匹配时,或者   如果没有要解析的主体,则为空对象({}),即Content-Type   未匹配,或发生错误。

在您的具体情况下,您要发送Content-Type: text/plain,所以只需使用:

app.use(bodyParser.text());