此问题在此处已有答案:
axios post request from frontend not recieving in node js backend(3个答案)
12天前关门了。
我有一些错误的问题。我一直试图修复它一些天,但无济于事。我正在做一个项目,每当我试图注册一个用户,我得到错误消息。这里是代码。
const express = require('express');
const bcrypt = require('bcrypt');
const session = require('express-session');
const flash = require('connect-flash');
const mongoose = require('mongoose');
const Admin = require('./model/admin.js');
const User = require('./model/user.js');
mongoose
.connect("mongodb://127.0.0.1:27017/tailor") // to connect to mongoDB
.then(()=>{console.log('Mongo server has started')})
.catch(()=>{console.log('Connection to Mongo Failed')})
const app = express()
app.use(flash());
app.set('view engine', 'ejs')
app.use(express.static('public'))
const port = 3000;
app.post('/register', async (req, res)=>{
try {
const {username, email, password, address, fullname, passport, phone} = req.body
console.log(req.body)
const foundUser = await User.findOne({username:username})
if(foundUser) {
req.flash('info', 'User Already Exist')
res.redirect('/signin')
}
const hashedPassword = await bcrypt.hash(password, 10)
const user = new User ({
username:username,
email:email,
passport:passport,
address:address,
fullname:fullname,
phone:phone,
passport:hashedPassword,
active:true,
role:'USER'
})
await user.save()
} catch (error) {
console.log(error)
}
res.redirect('/')
})
app.listen(port, ()=>{
console.log(`Server is running on port ${port}`)
})
字符串
这是我得到的错误消息。
TypeError: Cannot destructure property 'username' of 'req.body' as it is undefined.
at C:\Users\go\Downloads\project wdd 2\app.js:60:16
at Layer.handle [as handle_request] (C:\Users\go\Downloads\project wdd 2\node_module
s\express\lib\router\layer.js:95:5)
型
我会等待回应。
1条答案
按热度按时间nkkqxpd91#
你必须确保在定义路由之前定义了所有的配置。如果你这样做了,你可以继续使用express.bodyParser()。
示例如下:
个字符
最新版本的Express(4.x)已经将中间件从核心框架中分离出来,如果需要主体解析器,则需要单独安装
型
一旦你安装并使用了body解析器,它会给你给予期望的req.body值。