在 NodeJS 中使用表单的 Web 应用程序

Web Application with Forms in NodeJS

所以我正在开发一个网站,该网站的一部分将提供向我们发送有关如何改进它的评论的方法。此部分将询问用户的姓名、电子邮件地址,并有一个文本框。我希望用户能够单击“发送”并将该消息以及他们的姓名和电子邮件地址发送到指定的电子邮件地址。

这样网站的管理员就可以查看网站并尝试使内容更贴近用户的需求。我正在使用 NodeJS,但令我困惑的是如何实际实现它。我从来没有做过与后端通信之类的事情,所以我很困惑如何开始。

最初,我认为我可以用 HTML 制作一个 php 脚本来实现该功能,但知道 NodeJS 是一种服务器端脚本语言,我知道应该有一些方法可以合并在我的网络应用程序中。我用谷歌搜索,但我是 NodeJS 的初学者,所以我不能完全理解。如果有人可以帮助我解决这个问题,将不胜感激。

非常感谢!

您可以将 POST 中的所有数据发送到您的 node.js 服务器。这样您就可以将这些信息返回到您的请求正文中。我正在使用 Express.js.

HTML :

<form action='/sendMessage' method='POST'>
  <input type='text' name='username' id='username'/>  
  <input type='text' name='mail' id='mail'/>
  <input type='text' name='message' id='message'/>

</form>

Node.js :

app.post('/sendMessage', function(req, res){
  console.log(req.body.message) //your message
  console.log(req.body.username) //your username
  console.log(req.body.mail) //your mail

  //insert your code to send mail here
  });

为了发送邮件,我使用了易于使用的nodemailer模块(https://github.com/andris9/Nodemailer)。

您是否尝试保存人们填写的数据?如果是这样,除了 console.log 之外,除了上述解决方案之外,您还可以将数据写入以下工具之一:

或者。

mongo 有很多免费的云数据库,并提供了大量的入门示例。

当您必须使用网络表单创建页面时,您必须创建 GET 和 POST 请求。

在您的 GET 请求中,您必须显示有效的 HTML 页面。 为此你必须选择一个模板引擎,我使用 handlebar 但你可以自由选择你自己的(jade,ejs,...)。

示例:

//index.js
var express = require('express');
var app = express();
var expressHbs = require('express3-handlebars');

app.engine('hbs', expressHbs({extname:'hbs'}));
app.set('view engine', 'hbs');
app.get('/pages/contact', function(req, res){
   res.render('contact'); 
});

//contact.hbs 
// this form send a post request to /pages/contact
<form action='/pages/contact' method='post'>
  <input type='text' name='username' id='username'/>  
  <input type='text' name='mail' id='mail'/>
  <input type='text' name='message' id='message'/>
</form>

如果您想在表单上添加更多安全控制,请查看 helmet

根据您的POST请求,您必须执行一个操作,这里是保存表格(或通过电子邮件发送信息)。

  1. 您需要验证您的输入数据
  2. 您需要清理输入数据
  3. 您需要将数据处理到 mongodb、nodemailer 或 mandrill

看看express-validator

示例:

//index.js
var expressValidator = require('express-validator');

app.post('/pages/contact', function(req, res) {
 // VALIDATION
 // checkBody only checks req.body

 req.checkBody('username', 'Invalid username').notEmpty().isAlpha();
 req.checkBody('mail', 'Invalid email').isEmail();
 req.checkBody('message', 'Invalid message').notEmpty();

 // SANITIZE
 req.sanitize('message').escape().trim();
 var errors = req.validationErrors();
 if (errors) {
  res.send('There have been validation errors: ' + util.inspect(errors),  400);
 return;
 }
 // Proccess your data here via mandrill, nodemailer or mongoose.
});

另一种流行的解决方案是使用caolan/forms

PS: 发邮件可不是简单的事,看看mailchimp, mandrill, mailjet, mailgun ...