I am trying to connect mongodb server with node - javascript

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}.

Related

Error: Request failed with status code 404, React, Axios

I have built a form which I want to be able to send emails, to do this I have attempted to follow this youtube tutorial: https://www.youtube.com/watch?v=_3-By9QfFa0
However I am running into an issue where I am getting the error in the question title which is coming up in my console web browser when trying to submit the form. I realize the issue might have something to do with one of the routes somewhere but I just cant figure it out (unless it's something completely different).
schoolForm.js
const handleSubmit = async(e) => {
e.preventDefault();
try { //I also tried using only: "/send_mail" here like I have in server.js but it didnt work
await axios.post("http://localhost:3000/send_mail", {
name
});
}
catch (error) {
console.log(error);
}
}
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const bodyParser = require("body-parser");
const cors = require("cors");
const nodemailer = require("nodemailer");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.post("/send_mail", cors(), async (req, res) => {
let {text} = req.body;
const transport = nodemailer.createTransport({
host: "smtp-mail.outlook.com",
port: 587,
auth: {
user: "someone#hotmail.com",
pass: "password"
},
tls: {
rejectUnauthorized: false
}
});
await transport.sendMail({
from: "someone#hotmail.com",
to: "someone#hotmail.com",
subject: "subject",
html: `<p>${text}</p>`
})
});
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
Edit: The error I get in the browser:
Is there anyone that can help me solve this issue? Help would be greatly appreciated!
Your server is listening on port 4000. // server.js
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
You should use below URL for Axios call. // schoolForm.js
await axios.post("http://localhost:4000/send_mail", { // use port 4000 not 3000
name
});
You've set up your server to listen to port 4000 but your axios request is to port 3000.
Make sure you send the request to the correct port:
await axios.post("http://localhost:4000/send_mail", {
name
});
Also note the body-parser is deprecated and you should use express built-in middleware. so instead of:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
you should have:
app.use(express.urlencoded({extended: true}));
app.use(express.json());
and you can remove body-parser dependency.
You can read here to learn more about express built-in middleware and their optional properties.
EDIT:
The reason it wasn't working is because body is an object created by the middleware itself. Therefore req.body is undefined since the body object doesn't exists

Error: Cannot find module './keys_dev' Require stack

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.

Express does not properly follow server.js specifications

I am very new to learning and using the MERN stack. Currently, I am having a problem where when I try to run "nodemon server", the port opens on instead of despite specifying in server.js that I want it to start on 5000. I am having trouble sending POST requests to using Insomnia with the current server.js code below (I get a 404 error) and think that this might be causing the POST command to fail. Moreover, it also doesn't run console.log('Server is running on port: ${port}'); into the terminal I am running the server from. Any feedback is appreciated.
server.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB database connection established successfully");
});
const courseRouter = require("./routes/course");
const termRouter = require("./routes/term");
const userRouter = require("./routes/user");
app.use("/course", courseRouter);
app.use("/term", termRouter);
app.use("/user", userRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});

Cant connect to MongoDB in Firebase Functions

I am using Firebase Functions as the host for my MERN web app backend.
When I connect to MongoDB locally, it works and can run operations with the database. However, when I deployed to firebase functions, it failed to even connect to the database.
Code:
index.js
const functions = require('firebase-functions');
const server = require('./server.js');
exports.api = functions.runWith({ memory: "2GB", timeoutSeconds: 120 }).https.onRequest(server);
Part of server.js
const express = require("express");
const dotenv = require("dotenv");
const colors = require("colors");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const mongooseMethods = require("./database.js");
dotenv.config({ path: "./config/config.env" });
mongooseMethods.connectDB(process.env.MONGO_URL);
const PORT = process.env.PORT || 8080;
// set up app
const app = express();
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use("/api", routes); // /api routes
module.exports = app;
routes.js
const express = require("express");
const app = express.Router();
const testingApi = require('../controller/testing.js');
const authApi = require('../controller/auth.js');
// testing
app.get('/testing', testingApi.testing);
// user authentication
app.post('/user/register', authApi.createUser);
module.exports = app;
api/testing/ also works
database.js
const mongoose = require("mongoose");
const mongooseMethods = {
connectDB: async (url) => {
try {
console.log("Connecting to MongoDB")
const connection = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(`MongoDB Connected: ${connection.connection.host}`.cyan.bold);
return connection;
} catch (error) {
console.log(`Error: ${error.message}, Exiting`.red.bold);
process.exit(1);
}
}
}
module.exports = mongooseMethods;
auth.js
const User = require('../model/user.model.js');
const bcrypt = require("bcryptjs");
let authenticationApi = {
createUser: async (req, res) => {
try {
console.log("Creating");
let newUser = new User({
...req.body
})
let result = await newUser.save();
return res.status(200).json({ result: result });
} catch (error) {
return res.status(400);
}
}
}
module.exports = authenticationApi;
The error I received when sending request to firebase is
2020-02-27T02:34:46.334044912Z D api: Function execution took 30970 ms, finished with status: 'connection error'
Yet it runs perfectly fine in local. I also don't see the console log "connected to MongoDB". I'm guessing that the problem occurs in database.js that it failed to connect to mongo at the first place yet I don't know how to solve.
I am using the paid plan in Firebase and the outbound networking should be fine.
p.s. this is my first time posting here. thanks for your time and I apologize in advance if i'm breaking any rules.
Listening on a port is not a valid operation in cloud functions:
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Cloud Functions listens for you, using the URL that it was assigned, then delivers the request to your code. When you pass your express app to onRequest(), that's all wired up for you.
I suggest starting with a stripped down, simplified version of an app just to gain experience about how things work, then add in more as you get comfortable.
The reason for this to happen is that the architecture of Firebase Functions is not an actual server, but a serverless lambda-like endpoint. Since it cannot establish a lasting connection to the database, that it has to make a connection every time it received a request, the database sees this as spam and shut down further connection request from Firebase.
Therefore, you simply cannot host a complete express app with intended lasting connection in Firebase Functions.
More on that in this article

UnhandledPromiseRejectionWarning: Error: passport.initialize() middleware not in use

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

Categories

Resources