首页 > 解决方案 > 这个 PUT 语句有什么问题?

问题描述

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

服务器.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)

标签: node.jsexpressput

解决方案


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

所以在你的情况下:

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

推荐阅读