Express JS重定向到包含无效电子邮件的表单

时间:2018-01-14 16:16:56

标签: node.js forms reactjs express

我是nodeJS的新手,我一直在尝试使用验证创建注册表单。

验证部分已完成sql查询语句,但我无法从服务器端重定向到注册表单,并显示消息信息,例如“电子邮件地址已存在”。

如何在客户端'register.js'处理此问题?

register.js

      <form id='register-form' method="POST"  action="http://localhost:3306/register">

server.js

app.post('/register', (req,res) => {  
var email = req.body.email;
var password = req.body.password;

let sql = "SELECT * FROM user WHERE email='" + email + "'";

db.query(sql,(err,result) => {
if (err) throw err;

if (result.length > 0) {
  console.log("user already exists");
  res.redirect('http://localhost:3000/#/Register');
} else {
  insertUser(email,password);
  res.send(email + " has been added to database");
}

1 个答案:

答案 0 :(得分:0)

有多个查询...

  • 我不确定您的register.html文件是否位于使用快速静态中间件公开访问的任何文件夹(例如,public)中。如果是,我希望你设置静态中间件

<强> app.use(express.static( '公共'));

  • 如果电子邮件ID已存在于数据库中,您是否要将响应作为错误请求发送?,请在下面尝试
    如果(!result.length)
    res.status(400).json('电子邮件ID已存在');

OR

res.status(400).send(400,{错误:'电子邮件ID已存在'});

  • 您需要一个正文解析器来解析URL编码符号...示例代码对我有用:

    let express=require('express');
    let app = express();
    let server = require('http').createServer(app);
    
    var bodyParser = require('body-parser');
    var parseUrlencoded = bodyParser.urlencoded({ extended: false });
    
    app.use(express.static('public'));
    
    
    app.post('/register', parseUrlencoded, (req,res) => {
        var email = req.body.email;
        var password = req.body.password;
          if (!email) {
            res.writeHead(404,
                 {Location: 'http://localhost:3306/register.html'}
             );
            res.end();
           }
           else{
              res.status(200).json('email is not empty');
            }
    });
    server.listen(3306, ()=> console.log('app started'));
    

一些例子:Proper way to set response status and JSON content in a REST API made with nodejs and express

Error: Can't set headers after they are sent to the client