node.js入门中的事
发布于 2 年前 作者 gregLINm 1675 次浏览 来自 问答

相信这本书很多人都看过了。 在服务器接收到一些请求,在请求处理程序中返回相应的数据时,为什么这些数据用了UTF-8转码了还是乱码呢?

这是服务器的代码: var http = require(“http”); var url = require(“url”);

function start(route, handle) {   function onRequest(request, response) {     var postData = “”;     var pathname = url.parse(request.url).pathname;     console.log(“Request for " + pathname + " received.”);

request.setEncoding(“utf8”);

request.addListener(“data”, function(postDataChunk) {       postData += postDataChunk;       console.log(“Received POST data chunk '”+       postDataChunk + “’.”);     });

request.addListener(“end”, function() {       route(handle, pathname, response, postData);     });

}

http.createServer(onRequest).listen(8888);   console.log(“Server has started.”); }

exports.start = start;

这是路由的代码: function route(handle, pathname, response, postData) {   console.log("About to route a request for " + pathname);   if (typeof handle[pathname] === ‘function’) {     handle[pathname](response, postData);   } else {     console.log("No request handler found for " + pathname);     response.writeHead(404, {“Content-Type”: “text/plain”});     response.write(“404 Not found”);     response.end();   } }

exports.route = route;

这是请求处理程序的代码: function start(response, postData) {   console.log(“Request handler ‘start’ was called.”);

var body = ‘<html>’+     ‘<head>’+     ‘<meta http-equiv=“Content-Type” content=“text/html; '+     'charset=UTF-8” />’+     ‘</head>’+     ‘<body>’+     ‘<form action="/upload" method=“post”>’+     ‘<textarea name=“text” rows=“20” cols=“60”></textarea>’+     ‘<input type=“submit” value=“Submit text” />’+     ‘</form>’+     ‘</body>’+     ‘</html>’;

response.writeHead(200, {“Content-Type”: “text/html”});     response.write(body);     response.end(); }

function upload(response, postData) {   console.log(“Request handler ‘upload’ was called.”);   response.writeHead(200, {“Content-Type”: “text/plain”});   response.write("You’ve sent: " + postData);   response.end(); }

exports.start = start; exports.upload = upload;

求大牛帮下忙。

4 回复

如果我没有猜错的话,应该是 buffer 切割字符,会导致一些问题。

@hi363138911 好像没有用到buffer吧

论坛已经有过好几个关于这个的帖子了吧,自己搜搜, Buffer 相加是 toString 之后相加,必须Buffer.concat之类的方法来处理,参见《深入浅出NodeJS》;5年老帖: 小心buffer拼接的问题

@DevinXian 哇,最近一下发了三个问答,学习一些你这个贴先

回到顶部