POST with http.request instance -->node

var doPost = function(path,body){ //jsonBody: An object containing request data jsonBody = JSON.stringify(body); //headers: 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 //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 }; //returns http.requestClient instance of http.ClientRequest class 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 };

2 Responses

First snippet :)) welcome
Noob ;)

Write a 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.