POST with http.request instance --> node

var http = require('http'); var doPost = function(path,body){ //Convert object js with data to json string jsonBody = JSON.stringify(body); // An object containing request headers. var headers = { 'Content-Type': 'application/json', 'Content-Length': jsonBody.length }; /*host: A domain name or IP address of the server to issue the request to. Defaults to 'localhost' port: Port of remote server. Defaults to 80 path. Defaults to '/'. Should include query string example 'app/index' method: A string specifying the HTTP request method. Defaults to 'GET' headers: An object containing request headers */ var options = { host: '192.168.3.106', port: 600, path: path, method: 'POST', headers: headers }; /* http.request() returns an instance of the http.ClientRequest class. The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object */ var req = http.request(options, function(res) { res.setEncoding('utf-8'); var responseString = ''; res.on('data', function(data) { responseString += data; }); res.on('end', function() { var resultObject = JSON.parse(responseString); }); }); /* If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object */ req.on('error', function(error) { console.log("Problem with request: "+error.message); }); // write data to request body req.write(jsonBody); req.end(); //Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body };

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.