This article mainly introduces the amazing node. js reading notes node's Learning Summary. if you need a friend, you can refer to the project you will be doing this week (it should be said that this is the case all the time). let's make a conclusion based on different situations ~ This record is a summary of node learning, and the next one is the web front-end knowledge learned by the project.
1. HTTP
The HTTP module of node has been used in the first article. here we will learn the APIs that appear in several routines.
The code is as follows:
Var qs = require ('querystring ');
Require ('http'). createServer (function (req, res ){
If ('/' = req. url ){
Res. writeHead (200, {'content-type': 'Text/html '});
Res. end ([
'',
]. Join (''));
} Else if ('/url' = req. url & amp; 'post' = req. method ){
Var body = '';
Req. on ('data', function (chunk ){
Body + = chunk;
});
Req. on ('end', function (){
Res. writeHead (200, {'content-type': 'Text/html '});
Res. end ('Your name is'+ Qs. parse (body). name +'
');
});
} Else {
Res. writeHead (404 );
Res. end ('not found ');
}
}). Listen (3000 );
The parameter of the creatServer ([requestListener]) function is a callback function (req, res), where the req (request) is http. an instance of IncomingMessage, and res (response) is http. serverRrsponse instance.
We use the res url, method string, and two methods writeHead and end. As the name implies, a url is the URL that records the HTTP (everything behind the host name), and a method is the method that records the HTTP response.
WriteHead (statusCode, [reasonPhrase], [headers]) is used to send an http response header. this method is called only once when the message arrives, and must be called before the end method. If you call the write (chunk, [encoding]) or end ([data], [encoding]) method first, the system will automatically record the content in the response header that is not easy to see and changeable (in short, bad) and call the writeHead method.
The end method will send a message to the server, indicating that all the response information has been sent. Therefore, this method must be called each time the response is sent. When its parameters have content (such as routines), this method is equivalent to calling the write ('content', [encoding]) and end methods at the same time. This is quite convenient.
Next, the routine uses req. on to listen to events and bind them to req (message. The prototype is Emitter. on (event, listener). req is the object that generates the event. in the listener function, this points to the EventEmitter object associated with the current listener function.