![](/img/trans.png)
[英]Get user input from html form and write it to text, csv or other database file (express.js, node.js, html)
[英]passing user input of html form to express node js without routing to a new page
我正在嘗試使用imap在我的gmail收件箱中搜索電子郵件。 這將是服務器端郵件解析器。 為此,我使用了express,並且希望使用express接收用戶的輸入(來自搜索字段)。 但是,我在Internet上搜索的所有解決方案都使用app.post並將我帶到新頁面。 我不想在用戶界面中顯示任何新內容。 我只想接收用戶的輸入並將其提供給執行imap.search的函數。 有什么幫助嗎? 這是代碼:
索引
<!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的新路線。 如何避免這種情況?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.