传递html表单的用户输入以表示节点js而不路由到新页面

时间:2017-08-25 09:42:01

标签: javascript node.js express imap

我正在尝试使用imap在我的Gmail收件箱中搜索电子邮件。它将成为服务器端邮件解析器。为此,我使用了express,我希望使用express接收用户的输入(来自搜索字段)。但是,我在互联网上搜索的所有解决方案都使用app.post并将我带到一个新页面。我不想在用户界面中显示任何新内容。我只想接收用户的输入并将其提供给执行imap.search的函数。有帮助吗?这是代码:

的index.htm

<!doctype html>
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">

 Search: <input type = "text" name = "Search_value">  <br>
         <input type = "submit" value = "SEARCH">

</form>
</body>
</html>

test.js

var express = require('express')
var bodyParser = require('body-parser');
var app = express()
app.use(express.static('public'));
// use body parser to easy fetch post body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var Imap = require('imap'),
    inspect = require('util').inspect,
    MailParser = require("mailparser").MailParser;
var imap = new Imap({
  user: '***@gmail.com',
  password: '*****',
  host: 'imap.gmail.com',
  port: 993,
  tls: true
});
var fs = require('fs'), fileStream;
function openInbox(cb) {
  imap.openBox('INBOX', true, cb);
}


// route to '/index.htm' to return the html file
app.get('/index.htm', function (req, res) {
  res.sendfile('index.htm');
});

//route that receives the post body and returns your computation
app.post('/process_post', function (req, res) {
  passtoserver(req.body, res);
});

app.listen(8081);

function passtoserver(parms, res) {
  //get the parameters based on input name attribute from the html
  //and parse strings to numbers
  var m = parms.Search_value;
 // res.writeHead(200, { 'Content-Type': 'text/html' });
 res.end();
  openInbox(function(err, box) {
    if (err) throw err;
    imap.search([ 'ALL', ['FROM', m] ], function(err, results) {

    var f = imap.fetch(results, {
      bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
      struct: true
    });
    f.on('message', function(msg, seqno) {
      console.log('Message #%d', seqno);
      var prefix = '(#' + seqno + ') ';
      msg.on('body', function(stream, info) {
        var buffer = '';
        stream.on('data', function(chunk) {
          buffer += chunk.toString('utf8');
        });
        stream.once('end', function() {
          console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
        });
      });
      msg.once('attributes', function(attrs) {
        console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
      });
      msg.once('end', function() {
        console.log(prefix + 'Finished');
      });
    });
    f.once('error', function(err) {
      console.log('Fetch error: ' + err);
    });
    f.once('end', function() {
      console.log('Done fetching all messages!');
    });
  });
  });

}
imap.connect();

提交用户输入后,将打开一个名为process-post的新路径。怎么避免这个?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用:

https.request() API?

http.request()用于安全协议