Javascript res.write未返回预期值
代码如下:Javascript res.write未返回预期值,javascript,node.js,node.js-stream,node.js-connect,node.js-client,Javascript,Node.js,Node.js Stream,Node.js Connect,Node.js Client,代码如下: var http = require('http') var options = { hostname: 'localhost', method: 'POST', port: 8000, path: '/' } var s = 3; http.request(options, (res)=>{ }).end(s+'') http.createServer((req, res)=>{ res.writeHead(20
var http = require('http')
var options = {
hostname: 'localhost',
method: 'POST',
port: 8000,
path: '/'
}
var s = 3;
http.request(options, (res)=>{
}).end(s+'')
http.createServer((req, res)=>{
res.writeHead(200, {'Content-type': 'text/plain'})
var a = "";
req.on('data', (data)=>{
a+= data
})
req.on('end', ()=>{
res.write(a)
res.end()
})
}).listen(8000)
当预期返回值为3时,为什么服务器会向客户端返回无效信息?它确实返回3,但在您的示例中,您没有根据请求收集它 下面是代码的修改版本,它完成了整个请求/响应,就像一个简单的回音
var http = require('http')
var options = {
hostname: 'localhost',
method: 'POST',
port: 8000,
path: '/'
}
var s = 3;
http.request(options, (res)=>{
var str = '';
//another chunk of data has been recieved, so append it to `str`
res.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
res.on('end', function () {
console.log('res: ' + str);
});
}).end(s+'')
http.createServer((req, res)=>{
res.writeHead(200, {'Content-type': 'text/plain'})
var a = "";
req.on('data', (data)=>{
a+= data
})
req.on('end', ()=>{
console.log('req: ' + a)
res.write(a)
res.end()
})
}).listen(8000)
答复->
req: 3
res: 3
我解决了。这是变量a的可见性问题
var http = require('http')
var a = '';
var options = {
hostname: 'localhost',
method: 'POST',
port: 8000,
path: '/'
}
var s = 3;
http.request(options, (res)=>{
}).end(s+'')
http.createServer((req, res)=>{
res.writeHead(200, {'Content-type': 'text/plain'})
req.on('data', (data)=>{
a+= data
})
req.on('end', ()=>{
res.write(a)
res.end()
})
}).listen(8000)
您是否已确定res.write()当前返回的内容?res.write()Ok当前不返回任何内容。我建议您看看:。也许你已经有了。无论如何,他们在那个页面上有一个示例实现。看看您是否正在尝试实现一个节点HTTP服务器。它抽象了使用节点
http
api的许多细节。我需要它在不使用expressres的情况下工作。write()无论如何都不能工作。事实上,如果我在这个地址启动浏览器,在我启动显示白色屏幕的程序之后,然后清空,而不是看到数字3。