草庐IT

node.js - 无法连接到数据库MongoParseError : Unescaped at-sign in authority section

coder 2023-11-03 原文

我正在尝试连接到我的 nodeJS 项目中的 mongodb 服务器。我有一个数据库配置文件 DB.js

module.exports = {
    DB: 'mongodb+srv://user%40gmail.com:%24ugar@cluster-jfgsm.mongodb.net/test?retryWrites=true'
 };

用户名包含@ (%40) 标记,因为它是电子邮件 ID,密码包含 $(%24) 个字符。

我已经在我的 server.js 文件中将其连接为

    mongoose = require('mongoose'),
    config = require('./config/DB');

    const app = express();

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB,  { useNewUrlParser: true } ).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

并且我在我的 package.json 文件中添加了自定义 serve 选项来运行 nodemon。

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "serve": "nodemon server.js"
  },

但是当我尝试使用命令npm run serve 运行项目时,我在控制台中收到一条错误消息

Can not connect to the databaseMongoParseError: Unescaped at-sign in authority section

我也在堆栈溢出中搜索了很多问题,但对我没有任何帮助。

感谢任何帮助。 谢谢你

最佳答案

可以像这样对密码进行编码:

const DB_USER = 'user';
const PASSWORD = encodeURIComponent('hello@123'); 
const DB_URL = `mongodb://${DB_USER}:${PASSWORD}@ds331735.mlab.com:31772/any_db`;

如果您的密码中有@,您应该将其更改为%40

关于node.js - 无法连接到数据库MongoParseError : Unescaped at-sign in authority section,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52632830/

有关node.js - 无法连接到数据库MongoParseError : Unescaped at-sign in authority section的更多相关文章

随机推荐