我一直在使用 Node.js、express、mongodb 开发一个基本的 CRUD 应用程序,并使用我尝试自行设置的教程。我不确定为什么我的 POST 请求收到 302 响应。
router.route('/')
.get(function(req, res, next) {
mongoose.model('User').find({}, function(err, users) {
if (err) {
return console.error(err);
} else {
res.format({
html: function() {
res.render('users/index', {
title: 'All Users',
"users": users
});
},
json: function() {
res.json(users);
}
});
}
});
})
.post(function(req,res) {
// get values from post request
var name = req.body.name;
var iscool = req.body.iscool;
// call the create function from mongoose
mongoose.model('User').create({
name: name,
iscool: iscool
}, function(err, user) {
if (err) {
res.send("There was a problem connecting to db");
} else {
console.log(res.statusCode);
console.log('Creating POST for ' + user.name);
res.format({
html: function() {
// if successful, set header address bar to "users"
res.location("users");
res.redirect("/users");
},
json: function() {
res.json(user);
}
});
}
})
});
在我的 console.log(res.statusCode) 中,它返回 200 OK 响应,但在我的 Chrome 开发工具中,我在网络请求中收到 302 响应。我只是真的很困惑应该在哪里寻找我的错误。我的表单的操作设置为/users,路由器使用 (/users) 作为用户 Controller 和路由。
这也是表格:
<form name="adduser" action="/users" method="post">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="iscool">Are you cool?</label>
<input type="checkbox" value="true" name="iscool">
<div>
<div>
<button type="submit">Submit</button>
</div>
感谢任何帮助,并对间距表示歉意!
最佳答案
不确定您的应用中间件上是否已经有此功能,但您可以尝试使用 body-parser 中间件来解析 application/x-www-form-urlencoded :
在您的终端中:
npm install --save body-parser
您的表单:
...
<form method="POST" action="/users" enctype="application/x-www-form-urlencoded">
...
然后在您的应用中:
...
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
...
关于javascript - Nodejs POST 请求未发布到数据库并返回 302 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599642/