Node.js NodeJS将请求正文转换为大写并返回响应
在下面的代码中,我计划将req体转换为大写,并以res返回,还打印stdout,当我测试res时,它永远不会被提取,并且http连接永远处于活动状态。请有人在这里指出错误Node.js NodeJS将请求正文转换为大写并返回响应,node.js,sails.js,Node.js,Sails.js,在下面的代码中,我计划将req体转换为大写,并以res返回,还打印stdout,当我测试res时,它永远不会被提取,并且http连接永远处于活动状态。请有人在这里指出错误 var http =require('http'); var fs = require('fs'); var through = require('through2'); var server = http.createServer(function(req,res){ if(req.method
var http =require('http');
var fs = require('fs');
var through = require('through2');
var server = http.createServer(function(req,res){
if(req.method==='POST'){
req.pipe(through(function(buffer,encoding,next){
//console.log()
this.push(buffer.toString().toUpperCase());
next();
})).pipe(process.stdout).pipe(res) // If remove .pipe(process.stdout) then I get response.
}
//res.end(); -- If I enable this I do get a blank response with 200 OK
})
server.listen(process.argv[2]);
这应该行得通。您可以用console.log样式的消息替换任何log.info。从来没用过。下面是我解决这个问题的方法+我感谢埃文推荐班扬,我喜欢。我认为这比Evan的解决方案稍有改进,因为: 1) 它始终使用ES6函数语法 2) 它用于处理数据块的负担。它似乎是一个贯穿于through2的包装器模块,语法稍微简单一些。它只接受一个函数,并返回一个流,因此您可以像中间人流一样使用它,通过管道将输出流直接传输到响应流。你传递给它的函数需要一段数据(我认为是你的整个请求),让你在返回整个结果之前一次完成所有的工作 3) 我认为非POST请求的处理更好,包括错误处理,避免将所有逻辑包装在一个大的if块中
// hook up all my modules
var http = require('http')
var transformer = require('through2-map')
var bunyan = require('bunyan') // cool logger module
// locals
var listenPort = process.argv[2]
var logger = bunyan.createLogger({name: "http"})
var server = http.createServer((req, res) => {
// check for POST method
if (req.method !== 'POST') {
logger.error('405: Method Not Allowed')
res.writeHead(405)
res.end();
}
// pipe the request data into the transformer...
req.pipe(transformer((chunk) => {
// do the transformation with the chunk
// add a newline to avoid that weird '%' char at the end
return (chunk + '\n').toString().toUpperCase()
})).pipe(res) // then pipe the result to the response stream
})
server.listen(listenPort)
var http=require('http');
var uc=需要(“大写”);
http.createServer(函数(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(加州大学(“你好,世界!”);
res.end();
}).听(8080)代码>请你描述一下为什么这是答案?你应该写一些描述。不要重复你的答案。
// hook up all my modules
var http = require('http')
var transformer = require('through2-map')
var bunyan = require('bunyan') // cool logger module
// locals
var listenPort = process.argv[2]
var logger = bunyan.createLogger({name: "http"})
var server = http.createServer((req, res) => {
// check for POST method
if (req.method !== 'POST') {
logger.error('405: Method Not Allowed')
res.writeHead(405)
res.end();
}
// pipe the request data into the transformer...
req.pipe(transformer((chunk) => {
// do the transformation with the chunk
// add a newline to avoid that weird '%' char at the end
return (chunk + '\n').toString().toUpperCase()
})).pipe(res) // then pipe the result to the response stream
})
server.listen(listenPort)