旧行李 2011-05-28 00:44 采纳率: 25%
浏览 613
已采纳

如何在 node.js 中生成 HTTP POST 请求?

How can I make an outbound HTTP POST request, with data, in node.js?

转载于:https://stackoverflow.com/questions/6158933/how-to-make-an-http-post-request-in-node-js

  • 写回答

17条回答 默认 最新

  • derek5. 2011-05-28 00:50
    关注

    Here's an example of using node.js to make a POST request to the Google Compiler API:

    // We need this to build our post string
    var querystring = require('querystring');
    var http = require('http');
    var fs = require('fs');
    
    function PostCode(codestring) {
      // Build the post string from an object
      var 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 to
      var 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 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 read
    fs.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);
      }
    });
    

    I've updated the code to show how to post data from a file, instead of the hardcoded string. It uses the async fs.readFile command to achieve this, posting the actual code after a successful read. If there's an error, it is thrown, and if there's no data the process exits with a negative value to indicate failure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(16条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c