I have been trying to do the google oauth by following a tutorial and i am getting this error .
Though the above question has already been answered once but still I could not figure out as what is wrong in the order that i have used .
Here is my index.js
const express=require('express');
const app=express();
const cookieSession=require('cookie-session');
const keys=require('./config/keys');
const mongoose=require('mongoose');
const passport=require('passport');
require('./models/User');
require('./services/passport');
mongoose.connect(keys.mongoURI,{ useNewUrlParser: true });
require('./routes/authRoutes')(app);
app.use(
cookieSession({
maxAge:30*24*60*60*1000,
keys:[keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
const PORT=process.env.PORT || 5000;
app.listen(PORT);
Here is the github link to repo.github
Related
connecting the mongodb i found an error
index.js
require('dotenv').config();
const express=require('express')
const app= express;
const cors =require("cors");
//const port = 5000;
const connection = require("./db");
//db connection
connection();
//middleware
app.use(express.json())
app.use(cors());
const port = process.env.PORT || 8080
app.listen(port,()=>console.log(`Listening on port${port}...`));
i tried to add the connecting lines but cannot resolve the error and get error again ( throw err;
^
Error: Cannot find module './db'
Require stack:)
you does not share Fypdb file if you share it than I can tell what is problem in database file
in addition you missed call of express function
const app = express()
I have cloned a GitHub repo for reference. But i don't know what this .keys_dev refers to. Everything seems fine to me. But it is returning me error. Everything is in its place as expected. I hope anyone can help me. It requires stack that is unknown to me. It is requiring api that is already defined. I need to understand can anyone help?
const express = require("express");
const bodyPaser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
const users = require('./routes/api/users');
const level = require('./routes/api/levels');
const employee = require('./routes/api/employees');
const exception = require('./routes/api/exception');
const payslip = require('./routes/api/payslip');
const dashboard = require('./routes/api/dashboard');
const individualcost = require('./routes/api/individualcost');
const oneoffpayment = require('./routes/api/oneoffpayment');
const record = require('./routes/api/record');
const app = express();
//Body parser middleware
app.use(bodyPaser.urlencoded({ extended: false }));
app.use(bodyPaser.json());
app.use(cors())
//Db
const db = require("./config/keys").mongoURI;
//MongoDB connection
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport Middleware
app.use(passport.initialize());
//Passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/users', users);
app.use('/api/level', level);
app.use('/api/employee', employee);
app.use('/api/exception', exception);
app.use('/api/payslip', payslip);
app.use('/api/dashboard', dashboard);
app.use('/api/individualcost', individualcost);
app.use('/api/oneoffpayment', oneoffpayment);
app.use('/api/record', record);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App is running on port ${PORT}`));
const db = require("./config/keys").mongoURI;
This require is fetching application configurations from the local filesystem, in this case the db URI. Perhaps the author of the repo forgot to mention that detail? It's very likely that if you want to use a MongoDB you'll have to setup your own local or cloud database and create a file under config/keys that contains a mongoURI. This should look similar to this:
// this is the contents of ./config/keys
export default {
mongoURI: "mongodb+srv://project:your-mongo-uri-here",
};
If you're looking to start a mongo cluster on the cloud, I've been using cloud.mongodb for a small pet project, works like a charm and it has a free plan tier.
You can also run mongo locally and just point the mongoURI to your local mongo instance.
I tried to connect my mongo cluster with my local server but this error keeps on showing up. I am following a tutorial and it seems to work fine for the tutor but this error comes for me. I have provided the error screenshot below.
Error which comes up
The src has been provided
const express = require('express');
const env = require('dotenv');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
//routes
const userRoutes = require('./routes/user');
//constants
env.config();
//mongodb connect
//mongodb+srv://root:<password>#cluster0.9ylhh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
mongoose.connect(
`mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}#cluster0.9ylhh.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
).then(() => {
console.log('Database connected');
});
//middleware
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.listen(process.env.PORT, () => {
console.log(`server is running on port ${process.env.PORT}`);
});
I also did create a .env file with the credentials details and stuff
I tried to make a comment instead of an answer, but I don't have enough reputation.
If the error is authentication, maybe you have a problem with your credentials.
Does your username or password have any of these chars? : / ? # [ ] #
If they do, you'll have to URI encode them like so:
${encodeURIComponent(process.env.MONGO_DB_USER)}
${encodeURIComponent(process.env.MONGO_DB_PASSWORD)}
More info here: https://docs.mongodb.com/manual/reference/connection-string/#examples
BTW: You forgot the env part on your ${process.MONGO_DB_PASSWORD}.
I have a MERN application that runs fine on a Windows machine, but when trying to deploy it to a colleague's macOS machine we're getting the below error. Console logging process.env.DATABASE reveals it is undefined on the macOS machine. We tried setting the variable by running export NODE_ENV=development in the console but still get the same error.
index.js
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo');
const db = require('./database');
const router = require('./routes');
const app = express();
require('dotenv').config({ path: 'variables.env' });
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongoUrl: process.env.DATABASE })
}));
app.use('/api', router);
app.set('port', process.env.PORT || 8000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running on port ${server.address().port}`);
});
variables.env
NODE_ENV=development
DATABASE=database path
error in console:
> server#1.0.0 start
> node ./index.js
Assertion failed: You must provide either mongoUrl|clientPromise|client in options
/Users/user/Documents/ATT-main/server/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
throw new Error('Cannot init client. Please provide correct options');
^
Error: Cannot init client. Please provide correct options
at new MongoStore (/Users/user/Documents/ATT-main/server/node_modules/connect-mongo/build/main/lib/MongoStore.js:119:19)
at Object.<anonymous> (/Users/user/Documents/ATT-main/server/index.js:32:10)
What am I missing?
trying to get my data after creating it in mongodb from localhost:3000/todos/ and i get the error in node [UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client] i make use of the following
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
this is my app.js with the necessary route to localhost:3000/todos/
// Require Express
const express = require("express");
const app = express();
// Require Body-Parser
const bodyParser = require("body-parser");
// Require Cors
const cors = require("cors");
// Middlewares - [Set bodyParser before calling routes]
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Import Routes
const todoRoutes = require("./routes/todo");
// Setup Routes Middlewares
app.use("/", todoRoutes);
app.use("/todos", todoRoutes);
i want to see to see my output daata on localhost:3000/todos/ but i get it on localhost:3000/ . Thanks
ok i got a hang of it and it was my routes causing it i just adjusted where the route was to be directed.
// Import Routes
const todoRoutes = require("./routes/todo");
// Setup Routes Middlewares
app.use("/todos", todoRoutes);