Latest web development tutorials

Node.js GET / POST requests

In many scenes, our servers are required to deal with the user's browser, such as a form submission.

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

This chapter we will introduce Node.js GET / POST requests everyone.


GET request to obtain content

Since GET requests are embedded directly in the path, URL is the full path of the request, including the? Back part, so you can manually parse the contents back as a parameter GET request.

node.js parse the url module functions provide this functionality.

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);

Access in the browser http://localhost:3000/user?name=w3c&email=w3c@w3cschool.cc name=w3c&email=w3c@w3cschool.cc? Then view the returned results:

w3cnodejs

Get POST request content

POST request all content in the request body, http.ServerRequest property does not have a body content for the request, because the transmission wait request body can be a time-consuming job.

Such as uploading files, and many times we may not need to ignore the request body content, malicious POST request will greatly consume server resources, all node.js default will not resolve the request body, when you need it, you need to manually do.

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);