node.js - 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 ...');
});
解决方案
正如其他人所评论的那样,代码本身看起来应该可以工作。
所以直接的嫌疑人是URI,显然你不会发布完整的字符串让我们所有人看到,但想到的一个理论是你的密码有需要编码的字符,尝试在密码上使用javascripts encodeURIComponent 。
推荐阅读
- android - Cordova 插件语音识别在 getSupportedLanguages() 上失败
- c# - C# mvc5 通过控制器添加文本框
- reactjs - 使用 React Loadable 封装在 HOC 中的代码拆分路由组件
- r - 从 Excel 将浮点数作为字符串导入时出现问题。错误地添加精度
- firebase - Ionic 3 - 图像加载器不适用于 firebase 存储图像
- java - 如何使用 java 使用阿拉伯光词干分析器库
- java - 事件:请告诉我我是否理解?
- r - 矩阵类 (dgCMatrix) 的 rowsum 函数的等价物
- javascript - 我不拥有的页面上的自动点击按钮
- javascript - 具有向下钻取功能的谷歌图表列的棘手部分?