简体   繁体   English

如何在不使用node.js中的http模块的情况下发送http响应?

[英]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. 您的代码有两个主要问题。

  • Responses as formatted as headers followed by two sets of "\\r\\n", and then the content. 响应的格式为标头,后跟两组“ \\ r \\ n”,然后是内容。 The "\\r\\n" in your end() call should be in str . 您end()调用中的“ \\ r \\ n”应该在str You also are missing an 'n' from the first "\\r\\n". 您还缺少第一个“ \\ r \\ n”中的“ n”。
  • You are trying to pipe the contents of the readstream, which is great, but you are doing all of this inside of the steam's end(), so the pipe as nothing left to send because the data was all already emitted. 您正在尝试通过管道传输readstream的内容,这很棒,但是您正在Steam的end()内部进行所有这些操作,因此该管道不再需要发送,因为数据已经全部发出。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM