0
嗨,我正在關注一篇文章,無法真正通過POST api。 我正在使用模數連接到數據庫uri。數據庫連接無法在Express中工作
這是我的代碼。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://node:[email protected]: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看起來很好。
我可以使用本地主機沒有用戶名/密碼。但即使我嘗試使用用戶名/密碼也不行。所以基本上用戶名和密碼的uri在本地主機和遠程數據庫的情況下不起作用。 – kushalvm
在控制檯中顯示什麼錯誤? –
{[MongoError:auth failed] name:'Mongo Error',ok:0,errmsg:'auth failed',code:18} – kushalvm