我需要一个API从Android插入数据到mongodb,我遵循this,代码可以运行,没有错误,并且我使用POSTMAN尝试发布一些数据,它总是说无法获取任何答复,似乎有错误连接到192.168.1.105:3000/songs ,但我可以使用查找所有api和findByID。 这花了我数小时的时间,请大家帮忙,所以压低:(Mongodb插入数据API没有响应
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
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.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
路线
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:[email protected]: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.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
你能修正你的代码中的缩进吗?这真的很难阅读。 – JohnnyHK
对不起,1分钟;) –
@JohnnyHK好吧,我尽力而为;) –