lor*_*o-s 9 httprequest httpserver node.js
我正在尝试为node.js编写的应用程序实现一个简单的HTTP端点.我已经创建了HTTP服务器,但现在我一直在阅读请求内容主体:
http.createServer(function(r, s) {
console.log(r.method, r.url, r.headers);
console.log(r.read());
s.write("OK");
s.end();
}).listen(42646);
Run Code Online (Sandbox Code Playgroud)
请求的方法,URL和标头打印正确,但r.read()始终为NULL.我可以说这不是请求如何产生的问题,因为content-length服务器端的头大于零.
文档说 r是一个http.IncomingMessage实现可读流接口的对象,为什么它不起作用?
lor*_*o-s 14
好的,我想我找到了解决方案.该r流(其他事物一样在node.js的,愚蠢的我...)应在异步事件驱动的方式读取:
http.createServer(function(r, s) {
console.log(r.method, r.url, r.headers);
var body = "";
r.on('readable', function() {
body += r.read();
});
r.on('end', function() {
console.log(body);
s.write("OK");
s.end();
});
}).listen(42646);
Run Code Online (Sandbox Code Playgroud)
“可读”事件是错误的,它错误地在主体字符串的末尾添加了一个额外的空字符
使用'data'事件处理带有块的流:
http.createServer((r, s) => {
console.log(r.method, r.url, r.headers);
let body = '';
r.on('data', (chunk) => {
body += chunk;
});
r.on('end', () => {
console.log(body);
s.write('OK');
s.end();
});
}).listen(42646);
Run Code Online (Sandbox Code Playgroud)
来自官方文档 https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
Run Code Online (Sandbox Code Playgroud)
如果你想使用await,你可以将其转换为这样的promise:
// how to call function:
const body = await getBody(request);
// function:
function getBody(request) {
return new Promise((resolve) => {
const bodyParts = [];
let body;
request.on('data', (chunk) => {
bodyParts.push(chunk);
}).on('end', () => {
body = Buffer.concat(bodyParts).toString();
resolve(body)
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12980 次 |
| 最近记录: |