当我尝试创建新用户时,发布请求不起作用 [英] When i try to create a new user, the Post request doesn't work
本文介绍了当我尝试创建新用户时,发布请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Post 请求中:
in the Post request :
- 我尝试获取正文请求
- 使用快速验证器检查正文请求
- 如果有任何错误,请获取错误
- 如果错误>>重新加载 create_user 页面并在控制台中打印错误>>这里它在日志中给了我这个
{ location: 'body', param: 'username', msg: 'UserName is required', value: undefined },
- 否则将从模块架构创建一个新的用户对象,并使用 bycrypt 和哈希密码
- 然后它将保存 newUser 对象,如果有错误将
console.log
否则重定向到登录页面.
- i try to get the body request
- check the body request by using express validator
- get the error if there are any
- if error >> reload create_user page and print in the console the error >> here it gives me in the log this
{ location: 'body', param: 'username', msg: 'UserName is required', value: undefined },
- Else will create a new user object from the module schema and use bycrypt and hash the password
- Then it will save the newUser object and if there's an error will
console.log
otherwise redirect to the login page.
app.js 文件
根文件
const express = require('express');
const dotenv = require('dotenv');
const app = express(); //main app variable that represents the application
const morgan = require('morgan');
const bodyparser = require("body-parser"); //requiring the body parser
const path = require('path');
const expressValidator = require('express-validator');
const bycrypt = require('bcryptjs');
app.use(expressValidator())
//require the monogo db file
const connectDB = require('./server/database/connection');
dotenv.config({ path: 'config.env' });
//for the port variable
const PORT = process.env.PORT || 8080;
//requiring morgan file
//to log the request
app.use(morgan('tiny'));
// mongo db connection
connectDB();
//to show >> req.body
app.use(bodyparser.json());
//app.use(express.json());
app.use(bodyparser.urlencoded({ extended: true }));
createUserForm
POST 请求回调函数
createUserForm
POST REQUEST CALLBACK FUNCTION
exports.createUserForm = (req, res, next) => {
console.log('Post CREATE CATEGORY /create-user');
// getting the request body
const username = req.body.username;
const password = req.body.password;
const password2 = req.body.password2;
// check the body request by using express validator
req.checkBody('username', 'UserName is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'UserName is required').equals(req.body.password);
// get the error if there are any
let errors = req.validationErrors();
if (errors) {
//if there is an error so rerinder the templet
res.render('users/create_user.ejs', {
errors: errors //pass along the errors
}, console.log(errors));
} else {
let newUser = new userSchema({
username: username, // first is the attribute NAME of the model , second is the name value tag in the html file
password: password
});
bycrypt.genSalt(10, function(err, salt) {
bycrypt.hash(newUser.password, salt, function(err, hash) {
if (err) {
//ERROR PAGE
console.log(err);
}
/// Hashing the password
newUser.password = hash;
/// saving the user
newUser.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', 'You successfully registered')
res.redirect('/halalMunchies/login');
}
});
});
});
}
};
ejs文件中的表格:
<form action="/halalMunchies/create-user" method="post">
<div class="form-group">
<label class="control-label" for="username"> Username </label>
<input id="username" class="form-control" name="username" required autofocus="autofocus" />
</div>
<div class="form-group">
<label class="control-label" for="password"> Password </label> <input id="password" class="form-control" name="password" required autofocus="autofocus" type="password" />
</div>
<div class="form-group">
<label class="control-label" for="password2"> confirm Password </label> <input id="password2" class="form-control" name="password2" required autofocus="autofocus" type="password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Add User</button>
</div>
</form>
当我提交它时,它会重新加载表单页面,但数据库中没有发生任何事情.基本上它只是停在这部分......
When I submit it reloads the form page and nothing happened in the database. Basically it just stops at this part...
if (errors) {
//if there is an error so rerinder the templet
res.render('users/create_user.ejs', {
errors: errors //pass along the errors
}, console.log(errors));
推荐答案
您得到未定义的正文响应,您可能忘记包含正文解析中间件.
将此添加到 app.js
(server.js)
或您的应用程序的根文件中
Add this in app.js
(server.js)
or your root file of the app
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
它会解析您的请求并获得所有值...
It parses your request and you get all values...
这篇关于当我尝试创建新用户时,发布请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文