This week, the project was done scattered (it should be said that it has always been like this). The summary should be double-opened based on different situations~ This article records the learning summary about node, and the next article is the knowledge on the front-end of the web learned from the project.
1. HTTP
The HTTP module of node was exposed in the first article. Here we will learn the APIs that appear in several routines.
The code copy 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([
'<form method="POST" action="/url">',
'<h1>My form</h1>',
'<fieldset>',
'<label>Personal information</label>',
'<p>What is your name?</p>',
'<input type="text" name="name">',
'<p><button>Submit</button></p>',
'</form>',
].join(''));
}else if('/url' == req.url && '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('<b>Your name is <b>' + qs.parse(body).name + '</b></p>');
});
}else{
res.writeHead(404);
res.end('not found');
}
}).listen(3000);
The parameter of the creatServer([requestListener]) function is a callback function function(req, res), where req (request request) is an instance of http.IncomingMessage, and res (response) is an instance of http.ServerRrsponse.
We used the url, method string of res and two methods writeHead and end. As the name implies, url is the URL that records HTTP (everything after the hostname), and method is the method that records HTTP response.
writeHead(statusCode, [reasonPhrase], [headers]) is used to send an http response header information. This method is called only once when the message arrives and must be called before a method like end. If you do it instead, call the write(chunk, [encoding]) or end([data], [encoding]) method first, the system will automatically record a (invisible, unchangeable) response header content and call the writeHead method.
The end method will send a message to the server to indicate that the response is sent, so this method must be called every time the response is sent. When its parameters have content (such as routines), this method is equivalent to calling both write('content', [encoding]) and end methods. This is quite convenient.
Next, the routine uses req.on to listen for events and bind to req(message). Its prototype is Emitter.on(event, listener), req is the object that generates events, and in the listening function this points to the EventEmitter object associated with the current listening function.