我正在尝试发布表单数据,但是我在提交时会收到以下错误:
typeerror:无法在字符串'{" [对象对象(":"}'。
上创建属性'_id'。
我的帖子被成功捕获:
电影{id:" 8",firstName:" test",lastname:" test",英雄:"测试",照片:" xxxxxxxx"}
,但数据并未保存在mongoDB中。我使用的是Angular2的平均堆栈。
我的 server.js :
//Need to write the Express code
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var indexApi = require('./routes/index');
var movieApi = require('./routes/movie');
var port = 3000;
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// parse application/vnd.api+json as json
//app.use(bodyParser.json({ type: 'application/json' }))
app.use('/',indexApi);
// Register the movie.js file
app.use('/api',movieApi);
// View Engine
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
// Set static folder so that our all the things we read from client folder
app.use(express.static(path.join(__dirname,'client')));
app.listen(port,function(){
console.log("Server started at port number : "+ port);
});
我将数据发布如下:
my app.component.ts:
saveDetails(movieObj){
//Note: I am getting the movie object here
this.moviesService.saveMovie(movieObj).
subscribe((data=> this.movieObj = JSON.stringify(data._body);
console.log(this.movieObj);
);
}
and movies.service.ts:
saveMovie(movie){
//Note: I am getting the movie object here also
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://localhost:3000/api/movie',
movie, {
headers: headers});
}
movie.js:
router.post('/movie',function(req,res){
console.log("Under Post call....");
var movieObj= req.body;
// Note: here in the console everthing is comming as undefined thats is the problem
console.log("[_id]"+movieObj._id+"[id]"+movieObj.id+"[firstname]"+movieObj.firstname+"[lastname]"+movieObj.lastname+"[hero]"+movieObj.hero+"[photo]"+movieObj.photo);
db.movies.save(movieObj,function(err,docs){
if(err){
res.send(err);
}
res.json(docs);
});
});
我得到的输出是{" _id":" 590AAD3EC7133419F056BC77"," " {\" [object Object] \":\ \" \",\",\"" 590AA9C455F16D0EB4440673E \"} ":"}]
击中http://localhost:3000/api/电影url。
注意:目的是在MongoDB中保存数据。
mongoDB接受Object
,而您正在通过String
。
错误
var jsontest = JSON.stringify(movieObj);
正确
var jsontest=movieObj;
p.s:假设req.body是正确的电影对象。
您已经在使用app.use(bodyParser.json());
,将消息的主体解析为JavaScript对象。您可以直接传递,省略
var movieObj= req.body;
var jsontest = JSON.stringify(movieObj);
完全有
router.post('/movie',function(req,res){
console.log("Under Post call....");
db.movies.save(req.body, function(err,docs){ // req.body is js object, parsed by bodyParser
if(err){
res.send(err);
return;
}
res.json(docs);
});
});