【问题标题】:NodeJS - Retrieving Post Data Without BrowserNodeJS - 在没有浏览器的情况下检索帖子数据
【发布时间】:2016-04-01 05:18:07
【问题描述】:

我在尝试接收帖子数据时遇到问题,而无需先从 Web 浏览器运行 html 页面。我想知道是否有一种使用 NodeJS 的方法,有人可以运行给定的 html 文档,只检索 Post 数据和控制台输出。我需要这个才能允许在云或远程服务器环境中进行开发。

当前使用 Server.js :

var spawn = require('child_process').spawn; // Will not do for the situation of development within something similar to an Ubuntu Server
spawn(command, ["http://localhost:80/Develop/Client.html"]);
http.createServer(mainArgs).listen(options); // mainArgs is the function (req,res) callback

function mainArgs(req,res){
    if (req.method == 'POST') { // NodeJS is Getting what is posted...
        console.log("POST");

        var url_parts = url.parse(req.url, true);
        currentQuery = url_parts.query;

        req.on('end', function () {
            console.log("Body: " + currentQuery['stubScript']);
            writeHTML(currentQuery['stubScript']);
        });
    }

    ..... // HTML, JavaScript, & CSS Handled here
}

当前使用情况 Client.html :

<html>
     <head>
          //Posts data via XMLHttpRequest()
          <script src=devScript.js></script>
     </head>
     <body>
          <script>
               // Access Devscript functions and build page using javascript
          </script>
     </body>
</html>

当前使用 devScript.js:

function postIt(varname, variable) {

    var req = new XMLHttpRequest();
    var getParms = '?'+ varname + '=' + variable;

    req.open('POST', document.URL + getParms, true);

    req.onreadystatechange = function(){
        if (req.readyState == 4 && req.status == 200)
        {
            alert('PHPcall() : JSObject =' + varname );
        }
    };

    req.send(getParms);


} // Client is posting...

【问题讨论】:

    标签: node.js post get xmlhttprequest


    【解决方案1】:

    您正在寻找发送 html 请求。

    您可以使用 request 等模块或 wget 或 curl 等终端程序来执行此操作。

    但是,如果您需要在没有任何模块的情况下执行此操作(我建议使用模块,它们在许多方面都很理智,但以下不是)您可以使用本机 @987654323 执行类似于 this SO thread 中讨论的内容@ 和 querystring 模块。

    以下是该线程的代码:

    // 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);
      }
    });
    

    但是我强烈建议使用 request / wget / curl,因为错误处理是集中的,诸如表单(多部分、urlencoded 等)、json 数据和标头之类的东西在“客户端”端正确实现,大大减少了数量你会遇到的错误。

    【讨论】:

    • 我正在寻找一种严格的方法来做我需要的,而不使用中间件。我确信有一种方法可以使用一揽子 NodeJS 做同样的事情,但我很难找到它。
    • @StoneAgeCoder 我已经编辑了我的答案,以包含对使用“纯”nodejs 进行操作的参考。它演示了 POST 到 google 服务,您当然希望 POST 到其他地址。
    • 请求模块是一个我同意的好工具,但它没有提供我正在寻找的东西,上面的代码也没有。我可能正在尝试做一些不可能的事情。我认为该节点将具有无需浏览器即可执行 javascript 代码和 html 的功能。严格用于开发人员的服务器端测试目的。我正在使用 Ubuntu 服务器并享受控制台环境。我仍然可以通过在客户端上打开浏览器并导航到 url 来测试客户端,但是将此功能嵌入到 Node 中是有意义的。
    • @StoneAgeCoder 你的意思是你想伪装成一个浏览器,这样你就可以在前端运行js?看看这个列表中的一些东西:github.com/dhamaniasad/HeadlessBrowsers
    【解决方案2】:

    所以你想运行一个进程并将标准输出发布到一个 URL?您当前的用法会将 URL 作为参数传递给您生成的命令。因此该进程将负责将 POST 数据发送到 URL。

    要从生成过程中获取输出,请参阅:15339379

    要发出 POST 请求,请参阅:6158933

    如果这些答案有帮助,请务必点赞。

    更新:听起来你想接受一个 POST 请求;看到这个blog post

    【讨论】:

    • 我已经编辑了我的问题,以便更好地解释我的程序中使用更多代码的问题。我实际上是在尝试从客户端获取 POST 变量,而无需 spawn 方法实际打开 Web 浏览器。我只想要帖子数据,没有视觉效果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2016-04-22
    • 1970-01-01
    • 2020-10-22
    • 2011-02-04
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多