This week to do a project to do more scattered (should say always is so), summary on the basis of different situations double open bar ~ This record is about node Learning Summary, and the next is to do the project to learn the web front-end knowledge.
1.HTTP article
node 's HTTP module came in contact with the first article, where we learned about the APIsthat appeared in several routines.
1 varQS = require (' querystring ');2 3Require (' http '). Createserver (function(req, res) {4 if('/' = =Req.url) {5Res.writehead, {' Content-type ': ' text/html '});6 Res.end ([7' <form method= ' POST "action="/url ">",8' ,9' <fieldset> ',Ten' <label>personal information</label> ', One' <p>what is your name?</p> ', A' <input type= ' text ' name= ' name ' > ', -' <p><button>Submit</button></p> ', -' </form> ', the].join (' ')); -}Else if('/url ' = = Req.url && ' POST ' = =Req.method) { - varBODY = ' '; -Req.on (' Data ',function(chunk) { +Body + =Chunk; - }); +Req.on (' End ',function(){ ARes.writehead, {' Content-type ': ' text/html '}); atRes.end (' <b>your name is <b> ' + qs.parse (body). Name + ' </b></p> '); - }); -}Else{ -Res.writehead (404); -Res.end (' not found '); - } in}). Listen (3000);
function (req, res) , where request) is res ( response http. An instance of the Serverrrsponse .
we used it. res 's url , writehead, end . As the name implies, url is record url (everything behind the hostname), http response.
http response header information, this method is called only once when the message arrives, and must be in write (chunk, [encoding]) or writehead this method.
The end method sends a message to the server to indicate that the response was sent, so the method must be called each time the response is sent. When its arguments have content (such as routines), this method equals the simultaneous invocation of the write (' content ', [encoding]) and end methods. This is still quite handy.
Next, the routines use Req.on to listen for events and bind to req (message) . The prototype is Emitter.on (event, listener), req is the object that generated the event, and in the listener function this points to the current listener function's associated The Eventemitter object.