节点,快速和猫鼬:身份验证失败错误

时间:2019-04-03 00:56:41

标签: node.js express post mongoose mlab

我是Node / Express / Mongo / MLab和后端编程的新手。我正在尝试向MLab数据库提交发布请求,但遇到麻烦。我认为我的问题出在猫鼬和MLab。

Here is my Glitch project

我遇到错误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 ...');
});

1 个答案:

答案 0 :(得分:0)

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

所以直接怀疑者是URI, 显然,您不会发布完整的字符串供我们所有人查看,但是想到的一种理论是您的密码包含需要编码的字符, 尝试在密码上使用JavaScript encodeURIComponent