Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save umidjons/88fa0041e6dd583491dd83662d007d2c to your computer and use it in GitHub Desktop.
Save umidjons/88fa0041e6dd583491dd83662d007d2c to your computer and use it in GitHub Desktop.
Client/Server post request example in pure Node.js

Client/Server POST request example in pure Node.js

File server.js:

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

var server = http.createServer().listen(3000);

server.on('request', function (req, res) {
    if (req.method == 'POST') {
        var body = '';
    }

    req.on('data', function (data) {
        body += data;
    });

    req.on('end', function () {
        var post = querystring.parse(body);
        console.log(post);
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    });
});

console.log('Listening on port 3000');

File client.js:

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

var postData = querystring.stringify({
    msg: 'hello world'
});

var options = {
    hostname: 'localhost',
    port: 3000,
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length
    }
};

var req = http.request(options, function (res) {
    console.log('STATUS:', res.statusCode);
    console.log('HEADERS:', JSON.stringify(res.headers));

    res.setEncoding('utf8');

    res.on('data', function (chunk) {
        console.log('BODY:', chunk);
    });

    res.on('end', function () {
        console.log('No more data in response.');
    });
});

req.on('error', function (e) {
    console.log('Problem with request:', e.message);
});

req.write(postData);
req.end();

Server's output:

$ node index.js
Listening on port 3000
{ msg: 'hello world' }

Client's output:

$ node client.js
STATUS: 200
HEADERS: {"content-type":"text/plain","date":"Wed, 17 Aug 2016 09:22:04 GMT","connection":"close","transfer-encoding":"chunked"}
BODY: Hello World

No more data in response.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment