简体   繁体   English

这个 PUT 语句有什么问题?

[英]What is wrong with this PUT statement?

I am trying to write a PUT statement using Nodejs and Express, but am failing.我正在尝试使用 Nodejs 和 Express 编写 PUT 语句,但失败了。 I have included the entire error message here.我在这里包含了整个错误消息。 There is also a GET application, but that is simpler and seems to work as expected.还有一个 GET 应用程序,但它更简单并且似乎可以按预期工作。

server.js服务器.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  
  });
}); 

commandline命令行

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

error错误

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)

Using express , you can access the request body in req.body .使用express ,您可以访问req.body中的请求正文。

So in your case:所以在你的情况下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM