Node.JS将数据插入mongodb Web API,bodyParser问题

时间:2016-02-19 15:58:47

标签: node.js mongodb mongoose

我需要一个API来安卓才能将数据插入mongodb,我跟随this,但

 var song = req.body;  TypeError: Cannot read property 'body' of undefined

我谷歌很少回答,这需要安装bodyParser,所以我按照this安装bodyParser,但仍然得到

 var song = req.body;  TypeError: Cannot read property 'body' of undefined

我不知道我哪里做错了,请帮忙

应用代码

var express = require('express'),
songs = require('./routes/route');
var app = express();

var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();


app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
// create user in req.body
});

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

    app.get('/songs',songs.addSong);

路线cote

 var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXXXX:XXXXXXXX@ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');


db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});



exports.addSong = function(req, res) {
 var song = req.body;
 console.log('Adding song: ' + JSON.stringify(song));
 db.collection('songs', function(err, collection) {
 collection.insert(song, {safe:true}, function(err, result) {
  if (err) {
    res.send({'error':'An error has occurred'});
  } else {
    console.log('Success: ' + JSON.stringify(result[0]));
    res.send(result[0]);
  }
});
});
}

1 个答案:

答案 0 :(得分:0)

您未在jsonParser路线中使用GET /songs,只使用POST /songs路线。但是,GET请求通常没有请求正文。在这些情况下,值通常作为查询参数在url中传递,因此您可能希望改为查看req.query