首页 > 解决方案 > Node、Express 和 Mongoose:身份验证失败错误

问题描述

我是 Node/Express/Mongo/MLab 和一般后端编程的新手。我正在尝试向 MLab 数据库提交发布请求并遇到麻烦。我认为我的问题在于 Mongoose 和 MLab。

这是我的故障项目

我收到错误MongoDB connection error: { MongoError: Authentication failed.为什么我收到此错误?mongoose.connect我的功能和凭据有问题吗?MLab 是否设置不正确?

'use strict';

var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var validUrl = require('valid-url');
var dns = require("dns");
var cors = require('cors');
var app = express();

// Basic Configuration 
var port = process.env.PORT || 3000;


// Hooks up app to MLab MongoDB database by using the .env variable I created
// Doesn't work. Data is not submitted to MLab and /api/shorturl/new endpoint freezes up when form is submitted
mongoose.connect(process.env.MONGODB_URI, {useMongoClient: true});

/*
Also doesn't work
mongoose.connect(process.env.MONGODB_URI, {
    "auth":{"authSource": "admin"},
    "user": "admin",
    "pass": "password"
});
*/

// Should allow us to use promises with mongoose
mongoose.Promise = global.Promise;


var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));


// Sets up a Schema for the DB
var urlSchema = new mongoose.Schema({
  url: String,
  shortenedUrl: String
});


// Sets up a model for the DB
var Url = mongoose.model("Url", urlSchema);


app.use(cors());

/** this project needs to parse POST bodies **/
// you should mount the body-parser here
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.use('/public', express.static(process.cwd() + '/public'));

// parse application/x-www-form-urlencoded


app.get('/', function(req, res){
  res.sendFile(process.cwd() + '/views/index.html');
});


app.get("/api/shorturl/new", function (req, res) {
  res.sendFile(process.cwd() + '/views/form.html');
  //res.send({hi: "hi"});
});


app.post("/api/shorturl/new", urlencodedParser, function (req,res) {
  // Gets URL from form
  //var url = req.body.url;
  //console.log(url);

  var myData = new Url(req.body);

  console.log("myData : " + myData);

  myData.save()
    .then(item => {
      res.send("Successfully saved to DB");
    })
    .catch(err => {
      res.status(400).send("Unable to save to DB");
    });

});

app.listen(port, function () {
  console.log('Node.js listening ...');
});

标签: node.jsexpresspostmongoosemlab

解决方案


正如其他人所评论的那样,代码本身看起来应该可以工作。

所以直接的嫌疑人是URI,显然你不会发布完整的字符串让我们所有人看到,但想到的一个理论是你的密码有需要编码的字符,尝试在密码上使用javascripts encodeURIComponent


推荐阅读