高级节点中的数据库连接错误和 Express FCC Challenge-Serialization of a passport user
Posted
技术标签:
【中文标题】高级节点中的数据库连接错误和 Express FCC Challenge-Serialization of a passport user【英文标题】:Database connection error in advanced node and express FCC Challenge-Serialization of a passport user 【发布时间】:2020-05-26 13:07:32 【问题描述】:这是 freecodecamp 挑战链接请帮助我 FCC challenge link
我在 FCC 挑战中遇到数据库连接错误,谁能帮帮我。 This the image showing errors
我的故障项目链接 https://glitch.com/~chivalrous-pharaoh-mqknswso2j
Server.js 代码
‘use strict’;
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const fccTesting = require(’./freeCodeCamp/fcctesting.js’);
const session = require(‘express-session’);
const passport = require(‘passport’);
const ObjectId = require(‘mongodb’).ObjectId;
const mongodb = require(‘mongodb’).MongoClient;
const app = express();
fccTesting(app); //For FCC testing purposes
app.use(’/public’, express.static(process.cwd() + ‘/public’));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: true ));
app.set(‘view engine’, ‘pug’)
app.get(’/’, function (req, res)
res.render(’/app/views/pug/index.pug’, title: ‘Hello’, message: ‘Please login’)
)
mongodb.connect(process.env.DATABASE, (err, db) =>
if(err)
console.log('Database error: ’ + err);
else
console.log(‘Successful database connection’);
//serialization and app.listen
);
app.use(session(
secret: process.env.PORT,
resave: true,
saveUnintialized: true
));
passport.serializeUser((user, done) =>
done(null, user._id)
)
passport.deserializeUser((id, done) =>
mongodb.collection(‘users’).findOne(
_id: new ObjectId(id),
(err, doc) =>
if(err)
return done(err);
return done(null, doc);
);
);
app.use(passport.initialize);
app.use(passport.session);
app.listen(process.env.PORT || 3000, () =>
console.log("Listening on port " + process.env.PORT);
);
.env
SECRET=
MADE_WITH=
SESSION_SECRET=
DATABASE= 'mongodb+srv://Kuljeet:********@cluster0-gxlnb.mongodb.net/test?retryWrites=true&w=majority'
【问题讨论】:
【参考方案1】:我认为您必须在 server.js
中加载您的环境变量,这样您才能读取 process.env.DATABASE。
您可以使用dotenv
库。 https://www.npmjs.com/package/dotenv
npm install dotenv
在你的项目中
将require('dotenv').config()
添加到您的server.js
例如
‘use strict’;
require('dotenv').config();
const express = require(‘express’);
希望这能回答您的问题。
【讨论】:
以上是关于高级节点中的数据库连接错误和 Express FCC Challenge-Serialization of a passport user的主要内容,如果未能解决你的问题,请参考以下文章