[英]How to send a http response without using http module in node.js?
I need to implement a HTTP server in node.js without using http module. 我需要在node.js中实现HTTP服务器而不使用http模块。 How fun!
真有趣! I'm having trouble with sending the response socket.
我在发送响应套接字时遇到了麻烦。
I'm trying to fetch a file and so my code looks as follows: 我正在尝试获取文件,因此我的代码如下所示:
fileStream = fs.createReadStream('example.jpg');
fileStream.on("end", function (close) {
var str = "HTTP/1.1 200 OK\r\Content-Type: image/jpeg\r\n" //and some more headers.
socket.write(str);
socket.pipe(fileStream);
socket.end("\r\n");
});
What am I missing? 我想念什么?
I am of course using net module to get the socket and fs as well. 我当然使用net模块来获取套接字和fs。
There are two main issues with the code you have. 您的代码有两个主要问题。
str
. str
。 You also are missing an 'n' from the first "\\r\\n". Try something like this instead. 尝试这样的事情。 Create the read stream, send the response and pipe then rest.
创建读取流,发送响应并传递管道,然后休息。
var str = "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\n\r\n";
socket.write(str);
var fileStream = fs.createReadStream('example.jpg');
fileStream.pipe(socket);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.