Node Js response

I have a general question about Node Js response, and was hoping someone can explain what is actually going on when I do lets say res.WriteHead("blah blah").

So from what I understand in my html and javascript I make a request for a route. I check the request of the route and lets say its a get method. I do write head which will write the head of a http response. What will happen if I send res.write("some text");.

What i'm asking is can you explain the process and whats really going on with the communication between the client and server.

I'm a little confused on the response is this one message being sent back or is this like a stream.

Answers with as much explanation on the entire process would be greatly appreciated.

Some sample code of what im talking about. Please note im using NodeJS

// load http module var http = require('http');

//create the server var server = http.createServer(handleRequest);

//start the server server.listen(2000);

//request handler function function handleRequest(req, res) {

console.log(req.method+" request for "+req.url);

// content header
res.writeHead(200, {'content-type': 'text/plain'});

res.write("ohai!n");

// write message body and send
res.end("Hello, World!"); };

To Explain this we can consider an analogy where a response could be considered as a document having following entities - Status-Line ,( response-header) [ message-body ]

So by res.writeHead(200, {'content-type': 'text/plain'}); server is writing the status-line of the response document along with response-header 'content-type': 'text/plain'

By res.write("ohai!n"); server has started writing the contents of message body which will be considered complete by res.end("Hello, World!"); until then client will in stalled state waiting for server to provide response of the request

Concluding above that server side code there could be just one res.writeHead and res.end but multiple res.write could be used which will append messaged to message-body .

After the res.end is executed on server then the server sends the response in chunks using HTTP chunked transfer mechanism where each chunk is preceded by its size. The transmission ends when a zero-length chunk is encountered.

I am attaching request-response life-cycle

app.get('/check', function (req, res) {
res.writeHead(200, {'content-type': 'text/plain'});

res.write("ohai!n");
res.write("I am!n");
res.write("good!n");
res.end("Hello, World!");
})

this resulted in following response

ohai!
I am!
good!
Hello, World!
链接地址: http://www.djcxy.com/p/52516.html

上一篇: 生产服务器中的节点js API

下一篇: 节点Js响应