这个 PUT 语句有什么问题?

What is wrong with this PUT statement?

我正在尝试使用 Nodejs 和 Express 编写 PUT 语句,但失败了。我在这里包含了整个错误消息。还有一个 GET 应用程序,但它更简单并且似乎按预期工作。

server.js

app.use('/data', express.static('/views/data'));


app.put('/data/1-1', (req, res) => {
  let body = "";
  req.on('data', function (chunk) {
    body += chunk;
  });
  
  req.on('end', function () {
    do something  
  });
}); 

命令行

curl -X PUT http://localhost/data/1-1 -H "Accept: application/json" -H "Content-Type: application/json" --data-binary '[{"key": 1}]'

错误

ReferenceError: data is not defined
    at app.put (/home/w/server.js:172:15)
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/w/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/w/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)
    at /home/w/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/w/node_modules/express/lib/router/index.js:335:12)
    at next (/home/w/node_modules/express/lib/router/index.js:275:10)
    at /home/w/server.js:146:5
    at Layer.handle [as handle_request] (/home/w/node_modules/express/lib/router/layer.js:95:5)

使用express,您可以在req.body中访问请求正文。

所以在你的情况下:

app.put('/data/1-1', (req, res) => {
  console.log(req.body);
  // do something
  res.send(''); // sends an empty response
});