【问题标题】:res.write is not returning the expected valueres.write 没有返回预期值
【发布时间】:2018-01-31 08:32:04
【问题描述】:

这是代码:

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 时,服务器可能会向客户端返回无效信息?

【问题讨论】:

  • 你确定 res.write() 当前返回了什么?
  • 目前不使用 res.write() 返回任何内容
  • 好的。我建议看看:nodejs.org/api/http.html#http_http_request_options_callback。也许你已经有了。无论如何,他们在该页面上有一个示例实现。
  • 如果您正在尝试实现节点 HTTP 服务器,请查看 express。它抽象了很多使用节点 http api 的细节。
  • 我需要它在不使用 express 的情况下工作

标签: javascript node.js node.js-stream node.js-connect node.js-client


【解决方案1】:

它确实返回 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

【讨论】:

  • res.write() 无论如何都不起作用。以前也可以使用 console.log。
  • 事实上,如果我在地址127.0.0.1:8000启动浏览器,在我启动程序后显示白屏,然后为空,而不是看到数字3。
【解决方案2】:

我解决了。这是变量 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2020-06-30
    • 2018-08-17
    相关资源
    最近更新 更多