【问题标题】:Node.js user input from a website (not using Express.js)来自网站的 Node.js 用户输入(不使用 Express.js)
【发布时间】:2013-04-05 01:33:55
【问题描述】:

我仍然是 Node.js 的初学者,我正在尝试尽可能多的探索。

我知道 Express.js 是许多人用来在 Node.js 中创建网站的框架。

但是不使用 Express.js,我知道可以使用 'fs.readFile' 读取 .html 文件,然后在浏览器中“显示”这个 .html 文件。

有没有办法从这个网页获取用户输入(比如单击按钮,或填写一个框)到 Node.js 中?到目前为止,我还没有找到任何这样的例子。

【问题讨论】:

  • 只有核心模块?
  • 是的,只有核心模块

标签: node.js user-input fs


【解决方案1】:

是的,这是可能的。研究connect bodyParser's urlencoded function works如何。

当来自浏览器的请求进入时,节点会将其表示为可读的数据流。对于 Web 表单,模式为:

  1. 使用请求的dataend 事件将流中的数据块缓冲到单个字符串中。
  2. 根据其数据格式适当地解析该字符串。对于 web 表单,这通常是 urlencoded (application/x-www-form-urlencoded) MIME 类型

.

  var qs = require('qs'); //https://github.com/visionmedia/node-querystring
  function handle(req, res) {
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){
      //assemble the request from distinct chunks into a single string
      buf += chunk
    });
    req.on('end', function(){
      //OK, you have a usable string request body, parse it and handle it
      try {
        var formData = qs.parse(buf);
        //Yay, it parsed. Now you have your form data
        //depending on your form's html, you might have formData.email, for example
      } catch (err){
        //oops, respond with an error          
      }
    });
  }

【讨论】:

    【解决方案2】:

    Tutorial

    长话短说:

    http.createServer(function (req, res) {
        var data = '';
        req.on('data', function(chunk) {
            console.log("Received body data:");
            console.log(chunk);
            data += chunk.toString();
        });
    
        req.on('end', function() {
            console.log('Received Data: ', data);
            res.end();
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 2014-11-24
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多