我是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");
}
答案 0 :(得分:0)
有多个查询...
<强> app.use(express.static( '公共')); 强>
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