栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在node.js中发出HTTP POST请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在node.js中发出HTTP POST请求?

这是一个使用node.js向Google Compiler API发出POST请求的示例:

// We need this to build our post stringvar querystring = require('querystring');var http = require('http');var fs = require('fs');function PostCode(prestring) {  // Build the post string from an object  var post_data = querystring.stringify({      'compilation_level' : 'ADVANCED_OPTIMIZATIONS',      'output_format': 'json',      'output_info': 'compiled_pre',        'warning_level' : 'QUIET',        'js_pre' : prestring  });  // An object of options to indicate where to post to  var post_options = {      host: 'closure-compiler.appspot.com',      port: '80',      path: '/compile',      method: 'POST',      headers: {          'Content-Type': 'application/x-www-form-urlenpred',          'Content-Length': Buffer.byteLength(post_data)      }  };  // Set up the request  var post_req = http.request(post_options, function(res) {      res.setEncoding('utf8');      res.on('data', function (chunk) {          console.log('Response: ' + chunk);      });  });  // post the data  post_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 it  if(data) {    PostCode(data);  }  else {    console.log("No data to post");    process.exit(-1);  }});

我已经更新了代码,以显示如何从文件而不是硬编码的字符串发布数据。它使用async

fs.readFile
命令来实现此目的,并在成功读取后发布实际代码。如果有错误,则抛出该错误,如果没有数据,则该过程以负值退出以指示失败。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393365.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号