数据库连接在Express中不起作用

时间:2016-09-24 07:27:39

标签: node.js mongodb express curl

您好我正在阅读一篇文章,并且无法真正遇到POST api。 我使用模数连接到数据库uri。

这是我的代码。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
   mongoose.connect('mongodb://node:node@jello.modulusmongo.net:27017/hygeBe9b');

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

var port = process.env.port || 8080;

var router = express.Router();

//middleware to use for all requests

router.use(function(req, res, next){
console.log('Something is going on here !');

next();
})
router.get('/', function(req, res){
res.json({
    message: "Welcome to first API coding !"
})
});


router.route('/songs')
.post(function(req, res){
    var song = new Song();
    song.name  = req.body.title;

    song.save(function(err) {
        if (err) { res.send(err);}
        res.json({message : 'Song Created'});
    })
})
var Song = require('./models/songs');


app.use('/api', router);

app.listen(port);
console.log('Server running on port: ' + port);

模型文件

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var SongsSchema = new Schema({
 title: String
})

module.exports = mongoose.model('Song', SongsSchema);

这是我的邮递员请求代码

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Cache-Control: no-cache" -H "Postman-Token: 5b280358-3de8-b52c-590b-430f5f4b6766" -d 'title=demo' "http://localhost:8080/api/songs"

https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

重要的是,我如何调试代码以查看错误所在? API似乎很好。

1 个答案:

答案 0 :(得分:0)

可以检查这个并查看控制台中显示的错误:

var db = mongoose.connect('mongodb://localhost/dbName', function(err) {
    if (err) {
        console.log('Could not connect to MongoDB!', err);
    }
});

连接语法:

mongoose.connect('mongodb://[user]:[pass]@[hostAddress]:[port]/[databaseName]',callbackFunc)

for localhost

mongoose.connect('mongodb://localhost/databaseName',callbackFunc)

N.B:首先确保mongod正在运行