Node.js GET/POST requests


In many scenarios, our server needs to deal with the user's browser, such as form submission.

Forms submitted to the server generally use GET/POST requests.

In this chapter we will introduce Node.js GET/POST requests to you.


Get GET request content

Since the GET request is directly embedded in the path, the URL is the complete request path, including the part after ?, so you can manually parse the following part Content as parameter of GET request.

The parse function in the url module in node.js provides this function.

var http = require('http');
var url = require('url');
var util = require('util');

http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);

Visit http://localhost:3000/user?name=w3c&email=w3c@w3cschool.cc Then check the returned results:

w3cnodejs

Get the POST request content

All the content of the POST request is in the request body. http.ServerRequest does not have an attribute content for the request body. The reason is that waiting for the request body to be transmitted may be time-consuming. work.

For example, when uploading files, in many cases we may not need to pay attention to the content of the request body. Malicious POST requests will greatly consume server resources. All node.js will not parse the request body by default. You need to do it manually when you need to.

var http = require('http');
var querystring = require('querystring');
var util = require('util');

http.createServer(function(req, res){
    var post = '';     //定义了一个post变量,用于暂存请求体的信息

    req.on('data', function(chunk){    //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
        post += chunk;
    });

    req.on('end', function(){    //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
        post = querystring.parse(post);
        res.end(util.inspect(post));
    });
}).listen(3000);