【NodeJS】How to post to a request JSON data using node.js

client:


var http = require('http');


var post_req  = null,


    post_data = '{"login":"toto","password":"okay","duration":"9999"}';


var post_options = {


    hostname: '192.168.1.1',


    port    : '8080',


    path    : '/web/authenticate',


    method  : 'POST',


    headers : {


        'Content-Type''application/json',


        'Cache-Control''no-cache',


        'Content-Length': post_data.length


    }


};


post_req = http.request(post_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('Response: ', chunk);


    });


});


post_req.on('error'function(e) {


    console.log('problem with request: ' + e.message);


});


post_req.write(post_data);


post_req.end();


server:


var http = require('http');


var fs = require('fs');


var server = http.createServer(function (req, res) {


    if (req.method === "GET") {


        res.writeHead(200, { "Content-Type""text/html" });


        res.write("server started");


    } else if (req.method === "POST") { 


        var body = "";


        req.on("data"function (chunk) {


            body += chunk;


            res.write(body);


            console.log(body);


        });


    }


}).listen(8080);


Không có nhận xét nào

Được tạo bởi Blogger.