javascript - res.write 没有返回预期值

标签 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(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

关于javascript - res.write 没有返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828062/

相关文章:

javascript - angular.js "Hello World"应用程序无法正常工作

javascript - gulp中vinyl-buffer和gulp-streamify的目的是什么?

javascript - 使用requirejs优化器统一一个JS文件

node.js - 如何等待所有 Node 流完成/结束?

node.js - node.js 进程的额外 stdio 流

javascript - jquery p :last-child not working

javascript - 将 Apple 应用内购买添加到 Electron HTML/JS 应用

php - 检查 Javascript 并将其重定向到另一个页面

javascript - ionic 列表项文本溢出未调整列表项的高度

html - 如何在 nodejs 中通过 get 请求使用 req.body