Nodejs如何接受客户端put的数据?
Nodejs如何接受客户端put的数据?
昨天发起了一个问题,跟了下源码,发现问的不太准确更改如下。
客户端 采用ajax的put 向服务发送一段数据,
如 xhr.open(“put”,“123.html”,true);
xhr.send(“aaaaaaaaa”);
服务端为node.js 怎么获取 send出去的数据啊?即 aaaaaaaa
服务端这样写,函数没调用?正确的改怎么样写呢?
req.on(“data”, function(postDataChunk) { postData += postDataChunk; console.log(“Received POST data chunk '” + postDataChunk + “’.”); });
req.on("end", function() {
console.log("all data is '" + postData + "'.");
});
求助????????
3 回复
对于使用 Node.js 接收客户端通过 PUT 方法发送的数据,你需要设置一个 HTTP 服务器来监听 PUT 请求,并在请求处理函数中捕获数据。以下是如何做到这一点的一个示例:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'PUT') {
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// 此时 body 就是客户端发送的数据
console.log("Received PUT data: " + body);
// 你可以根据需要对 body 进行进一步处理
res.end('Data received successfully');
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
}
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
在这个例子中,我们创建了一个 HTTP 服务器来监听端口 3000。当接收到 PUT 请求时,服务器会监听 data
事件以累积请求体中的所有数据片段,然后在 end
事件触发时将这些片段组合成完整的请求体,并打印出来。最后,服务器返回一条成功接收数据的消息。
注意,这个示例假设你的客户端使用了标准的 AJAX PUT 请求方式。如果你使用的是像 axios
或其他库发送请求,确保你正确地设置了请求方法和数据格式。