node.js - 这个 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)
解决方案
使用express
,您可以访问 中的请求正文req.body
。
所以在你的情况下:
app.put('/data/1-1', (req, res) => {
console.log(req.body);
// do something
res.send(''); // sends an empty response
});
推荐阅读
- javascript - 如何在 AngularJS 中访问 DOM 元素
- swift - 每次呈现视图控制器时呈现插页式广告 - Swift 4
- python - 给定两个 ndarray,我如何以 numpy-ish 方式提取属于索引子集的条目?
- python - Pytorch RuntimeError:聚集中的索引无效
- php - 除了“get”命名的之外,Slim Framework 路由返回未找到
- html - 无法为卡片打开设置动画
- netty - netty - ssl/tls 双向认证
- docker - 设置 IP 表失败:无法启用 NAT 规则
- c - Nvidia/AMD 不支持 glsl 中的 uint64_t?
- r - 如何通过 quanteda 中至少有 n 个术语的文档过滤 dfm?