// We need this to build our post stringvar querystring = require('querystring');var http = require('http');var fs = require('fs');
function PostCode(codestring) {// Build the post string from an objectvar post_data = querystring.stringify({'compilation_level' : 'ADVANCED_OPTIMIZATIONS','output_format': 'json','output_info': 'compiled_code','warning_level' : 'QUIET','js_code' : codestring});
// An object of options to indicate where to post tovar post_options = {host: 'closure-compiler.appspot.com',port: '80',path: '/compile',method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded','Content-Length': Buffer.byteLength(post_data)}};
// Set up the requestvar post_req = http.request(post_options, function(res) {res.setEncoding('utf8');res.on('data', function (chunk) {console.log('Response: ' + chunk);});});
// post the datapost_req.write(post_data);post_req.end();
}
// This is an async file readfs.readFile('LinkedList.js', 'utf-8', function (err, data) {if (err) {// If this were just a small part of the application, you would// want to handle this differently, maybe throwing an exception// for the caller to handle. Since the file is absolutely essential// to the program's functionality, we're going to exit with a fatal// error instead.console.log("FATAL An error occurred trying to read in the file: " + err);process.exit(-2);}// Make sure there's data before we post itif(data) {PostCode(data);}else {console.log("No data to post");process.exit(-1);}});
var requestify = require('requestify');
requestify.post('http://example.com', {hello: 'world'}).then(function(response) {// Get the response body (JSON parsed or jQuery object for XMLs)response.getBody();});
var request = require('request');
var options={'key':'28','key1':'value','key2':'value'}
request({url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?minorRev="+options.key+"&cid="+options.key1+"&apiKey="+options.key2,method:"POST",json:true},function(error,response,body){console.log(body)});
var bodyString=JSON.stringify(body)var _headers = {'Content-Length': Buffer.byteLength(bodyString)};
在写入请求之前:
request.write( bodyString );
关于Get和Post方法:
timeout可以作为socket断开连接出现,所以你必须像这样注册它的处理程序:
request.on('socket', function (socket) {socket.setTimeout( self.timeout );socket.on('timeout', function() {request.abort();if(timeout) return timeout( new Error('request timed out') );});});
而request处理程序是
request.on('timeout', function () {// Timeout happend. Server received request, but not handled it// (i.e. doesn't send any response or it took to long).// You don't know what happend.// It will emit 'error' message as well (with ECONNRESET code).req.abort();if(timeout) return timeout( new Error('request timed out') );});
我强烈建议把两个处理人都登记。
响应体是块的,所以你必须在data处理程序中连接块:
var body = '';response.on('data', function(d) {body += d;});
var https = require('https');
/*** HOW TO Make an HTTP Call - POST*/// do a POST request// create the JSON objectjsonObject = JSON.stringify({"message" : "The web of things is approaching, let do some tests to be ready!","name" : "Test message posted with node.js","caption" : "Some tests with node.js","link" : "http://www.youscada.com","description" : "this is a description","picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png","actions" : [ {"name" : "youSCADA","link" : "http://www.youscada.com"} ]});
// prepare the headervar postheaders = {'Content-Type' : 'application/json','Content-Length' : Buffer.byteLength(jsonObject, 'utf8')};
// the post optionsvar optionspost = {host : 'graph.facebook.com',port : 443,path : '/youscada/feed?access_token=your_api_key',method : 'POST',headers : postheaders};
console.info('Options prepared:');console.info(optionspost);console.info('Do the POST call');
// do the POST callvar reqPost = https.request(optionspost, function(res) {console.log("statusCode: ", res.statusCode);// uncomment it for header details// console.log("headers: ", res.headers);
res.on('data', function(d) {console.info('POST result:\n');process.stdout.write(d);console.info('\n\nPOST completed');});});
// write the json datareqPost.write(jsonObject);reqPost.end();reqPost.on('error', function(e) {console.error(e);});
var options = {method: 'POST',uri: 'http://api.posttestserver.com/post',body: {some: 'payload'},json: true // Automatically stringifies the body to JSON};
rp(options).then(function (parsedBody) {// POST succeeded...}).catch(function (err) {// POST failed...});