javascript - 如何使用客户端作为放置请求的一部分发送的 express 访问服务器端的数据

标签 javascript node.js angular express

以下是我的 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/

相关文章:

node.js - FontAwesome 的 Jade 助手

javascript - JS 中的递归挑战将所有可能的数组键组合为 true |错误版本,我附上输入和输出

angular - 将 WebView 添加到渐进式 Web 应用 (PWA)?

java - 错误: XHR failed loading: GET "http://localhost:8080/home" in agular

javascript - 使用计算属性名称作为导出函数名称

javascript - 限制 Reducer 的结果

javascript - 使用Javascript读取当前目录的文件名

javascript - 我应该使用 fetch() 和 .then 还是 async/await

angular - forkJoin 不适用于 AngularFire2 valueChanges

javascript - 如何关闭 webpack linting