这是我在学习imooc上node实战时遇到的问题,视频中老师用了以下代码
var app = express()
var express = require('express')
app.use(express.bodyParser())
最后在视频中运行无误。
我已经知道express.bodyParser()
在新版本中被取消
也知道了替代方案中的extend:true
的作用
可是当我把代码修正过来之后,仍然报错
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))//将表单数据格式化
^[{ [ValidationError: Movie validation failed]
message: 'Movie validation failed',
name: 'ValidationError',
errors:
{ year:
{ [CastError: Cast to Number failed for value "2015/12/31" at path "year"]
message: 'Cast to Number failed for value "2015/12/31" at path "year"',
name: 'CastError',
kind: 'Number',
value: '2015/12/31',
path: 'year',
reason: undefined } } }
/Users/Vagor/Desktop/easy_movie/app.js:123
res.redirect('/movie/' + movie._id)
^
TypeError: Cannot read property '_id' of undefined
at /Users/Vagor/Desktop/easy_movie/app.js:123:37
at /Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/document.js:1747:19
at handleError (/Users/Vagor/Desktop/easy_movie/node_modules/hooks-fixed/hooks.js:40:22)
at _next (/Users/Vagor/Desktop/easy_movie/node_modules/hooks-fixed/hooks.js:46:22)
at fnWrapper (/Users/Vagor/Desktop/easy_movie/node_modules/hooks-fixed/hooks.js:186:18)
at /Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/schema.js:234:13
at complete (/Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/document.js:1131:7)
at /Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/document.js:1160:20
at ObjectId.SchemaType.doValidate (/Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/schematype.js:654:22)
at /Users/Vagor/Desktop/easy_movie/node_modules/mongoose/lib/document.js:1156:9
at nextTickCallbackWith0Args (node.js:433:9)
at process._tickCallback (node.js:362:13)
app.post('/admin/movie/new', function(req, res) {
var id = req.body.movie._id
var movieObj = req.body.movie
var _movie
if (id !== 'undefined') {
Movie.findById(id, function(err, movie) {
if (err) {
console.log(err)
}
_movie = _.extend(movie, movieObj)
_movie.save(function(err, movie) {
if (err) {
console.log(err)
}
res.redirect('/movie/' + movie._id)
})
})
}
else {
_movie = new Movie({
doctor: movieObj.doctor,
title: movieObj.title,
country: movieObj.country,
language: movieObj.language,
year: movieObj.year,
poster: movieObj.poster,
summary: movieObj.summary,
flash: movieObj.flash
})
_movie.save(function(err, movie) {
if (err) {
console.log(err)
}
res.redirect('/movie/' + movie._id)
})
}
})
var express = require('express')
var port = 3000
var path = require('path')
var bodyParser = require('body-parser')
var _ = require('underscore')
var mongoose = require('mongoose')
var Movie = require('./models/movie.js')
var app = express()
mongoose.connect('mongodb://localhost/imooc')
app.set('views','./views/pages')
app.set('view engine','jade')
// app.use(express.bodyParser())
// app.use(bodyParser.urlencoded())
app.use(bodyParser.urlencoded({ extended: true }))//将表单数据格式化
app.use(express.static(path.join(__dirname,'bower_components')))//告诉浏览器请求样式就到此文件夹查找,dirname就是当前目录
app.listen(port)
app.locals.moment = require('moment')
console.log('imooc started on port:' + port)
//index page
app.get('/',function(req,res){
Movie.fetch(function(err,movies){
if (err) {
console.log(err)
}
res.render('index',{
title:'imovie 首页',
movies:movies
})
})
})
//detail page
app.get('/movie/:id',function(req,res){
var id = req.params.id
Movie.findById(id, function(err,movie){
if (err) {
console.log(err)
}
res.render('detail',{
title:'imovie' + movie.title,
movie:movie
})
})
})
//admin page
app.get('/admin/movie',function(req,res){
res.render('admin',{
title:'imovie 后台录入页',
movie:{
title: '',
doctor: '',
country: '',
year: '',
language: '',
summary: '',
poster: '',
flash: ''
}
})
})
//admin update movie
app.get('/admin/update/:id',function(req,res){
var id = req.params.id
if (id) {
Movie.findById(id,function(err,movie){
res.render('admin',{
title:'imovie 后台更新页',
movie:movie
})
})
}
})
//admin post movie
// admin post movie
app.post('/admin/movie/new', function(req, res) {
var id = req.body.movie._id
var movieObj = req.body.movie
var _movie
if (id !== 'undefined') {
Movie.findById(id, function(err, movie) {
if (err) {
console.log(err)
}
_movie = _.extend(movie, movieObj)
_movie.save(function(err, movie) {
if (err) {
console.log(err)
}
res.redirect('/movie/' + movie._id)
})
})
}
else {
_movie = new Movie({
doctor: movieObj.doctor,
title: movieObj.title,
country: movieObj.country,
language: movieObj.language,
year: movieObj.year,
poster: movieObj.poster,
summary: movieObj.summary,
flash: movieObj.flash
})
_movie.save(function(err, movie) {
if (err) {
console.log(err)
}
res.redirect('/movie/' + movie._id)
})
}
})
//list page
app.get('/admin/list',function(req,res){
Movie.fetch(function(err,movies){
if (err) {
console.log(err)
}
res.render('list',{
title:'imovie 列表页',
movies:movies
})
})
})
//list delete movie
app.delete('/admin/list',function(req,res){
var id = req.query.id
if (id) {
Movie.remove({_id:id},function(err,movie){
if (err) {
console.log(err)
}
else{
res.json({success:1})
}
})
};
})
情各位指出错误的根源并指正,谢谢!
当我submit(post方式)表单数据为数字时,可以提交并返回,但仍有文件传输错误。
但是当我提交的是字符串(或者说是中文时,我不知道是什么原因),就会产生上述错误,服务器被强制关闭
我已经将代码上传至github,希望各位能帮我查看一下问题
In addition to bodyParser(urlencoded()), you also need a bodyParser(json()). Just upgrade Express to 4.x and use the generator to generate a project.
After looking at the code, there is no logical problem, but it lacks security verification. The main problem is that the id you sent the request is wrong. The correct format of Object_id is a 24-character hexadecimal number, for example :
568761de48b492fd35046a45
. The reason why the program crashed was that there was no verification of the url address bar. Because under normal circumstances, the id parameter passed by the client is the ObjectId obtained from the background, but for the sake of rigor, the following processing is done:I encountered the same problem, how did you solve it? It has been bothering me for two days
The error reported by the poster is
[{ [ValidationError: Movie validation failed]
, and the incoming data has not passed the attribute verification ofMovie
.When the poster writes the route, if there is
err
, please be sure to usereturn
. For example, the poster_movie.save()
needs to be written in the following form, otherwise you will be confused if there is an error.mogoose’s
model.save(function(err){})
has only one callback parametererr
http://mongoosejs.com/docs/models.html Constructing documents section
_id
has been generated when new.So it is written as follows:
I don’t know if the questioner has solved the problem~
I also encountered the same problem.
But in the end it was found that there was a problem with the indentation of admin.jade
If the questioner hasn’t solved the problem yet, you can try it (●'◡'●)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In fact, you don’t need to rush to post a lot of code. Track your data first and you will know where there is a problem. The error message is obviously that the thing you are using does not have the _id field, so just check what the thing you are currently using is. Tracking starts when the data comes out of the database, and the console output looks at the data structure and type. Then every time you operate on the data, check whether the structure and type of the data have changed. In the end, just track down where you went wrong and see if the output is exactly what you want.