const express = require("express");
const app = express();
const path = require("path");
require("dotenv").config({ path: path.resolve(__dirname, "./.env") });
const mongoose = require("mongoose");
console.log(process.env.DB_CONNECT);
// mongoose.connect(
// process.env.DB_CONNECT,
// { useNewUrlParse: true },
// () => console.log("connected to db!")
// );
const authRoute = require("./routes/auth");
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("serve is up"));
const router = require("express").Router();
router.post("/register", (req, res) => {
res.send("Register");
});
// router.post("/login");
module.exports = router;
DB_CONNECT="mongodb+srv://<username>:<password>#fypdatabase.quhdl.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
I have installed mongoose, express, dotenv. I tried to connect user to the data base using dotenv, without dotenv it was working perfeclty fine:
moongoose.connect("url",{useNewUrlParser:true},console.log('connected');
But when I tried with dotenv and consolo logging the process.env.DB_CONNECT to see if there is value or not and it is showing undefined
const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();
// console.log(process.env.MONGO_URL);
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('database connected');
}
);
Maybe you specified wrong path to the .env file. Try to put .env file in the root of your application. Then just use config() without path option. .env package will by default check it for you in the root of the application.
require("dotenv").config();
Related
I'm having trouble getting my axios .get in production with React.
I created a nodeJS server with express to render my react page each time I want to refresh my page. That work.
But the problem is that it block my axios .get(). So, my page show normaly without the data I normaly get in dev mode.
BackEnd => server.js with sequelize module to manage my database
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
db.sequelize.sync().then(() => {
app.listen();
});
BackEnd => GovernmentCreate.js
const express = require('express');
const router = express.Router();
const { GovernmentCreate } = require('../models');
router.get("/", async (req, res) => {
const listOfGovernments = await GovernmentCreate.findAll({
include: {all: true}
});
res.json(listOfGovernments);
});
FrontEnd => Part of code inside my GouvernmentWall.js that is called with url https://www.mon-gouvernement.fr/gouvernement-galerie
const [governmentList, setGovernmentList] = useState([]);
axios.get(`https://www.mon-gouvernement.fr/GovernmentCreate`)
.then((res) => {
console.log(res.data);
const resData = res.data;
setGovernmentList(sortResData);
}).catch((err) => {
console.log(err);
});
After multi-searching I'm thinking that the problem come from these lines in my server.js :
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
But if I remove it, when I try to refresh my page I'm getting a white page diplay Cannot GET /gouvernement-galerie.
So I'm stocking with this issu. I need your help to move forward.
Problem solve !
As #jonrsharpe mentioned, I have to switch my .get('/*' to the bottom of my routes. My server.js look like :
const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');
app.use(express.json());
app.use(cors());
const db = require('./models');
app.use(express.static(path.join(__dirname, 'build')));
//************************************************
// ROUTES
//************************************************
const governmentCreateRouter = require('./routes/GovernmentCreate');
app.use("/governmentCreate", governmentCreateRouter);
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
db.sequelize.sync().then(() => {
app.listen();
});
I am trying to create DB using following snippet
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
const port = 80;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/griData", {useNewUrlParser: true, useUnifiedTopology: true}, (err)=> {
if(err){
console.log(err);
}
});
console.log(mongoose.connection.readyState);
app.get("/", (req, res)=> {
res.render("main");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
but when I check dbs from mongo shell, I don't see any db. What am I missing? Thanks
I am trying to register the user to mongodb atlas for registration and login but i am geting an error 404.
here is full link to mycode
https://github.com/badrinathareddyr/falcon.git
server.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const authRoute = require('../backend/routes/auth')
//connect to database
dotenv.config({ path: __dirname + '/.env' });
mongoose.connect(
process.env[DB_CONNECT], { useNewUrlParser: true }, () =>
console.log('connected to db!')
);
//Middleware
app.use(express.json());
//middlewareroutes
app.use('/register', authRoute);
app.listen(3000, () => console.log('server up and running'));
auth.js file
var express = require('express');
const router = express.Router();
const User = require('../models/User');
const bcrypt = require('bcryptjs');
router.post('/register', function (req, res) {
if (!req.body.email || !req.body.password) {
res.json({ success: false, msg: 'Please pass email and password.' });
} else {
var newUser = new User({
email: req.body.email,
password: req.body.password
});
// save the user
newUser.save(function (err) {
if (err) {
return res.json({ success: false, msg: 'Email already exists.' });
}
res.json({ success: true, msg: 'Successful created new user.' });
});
}
});
module.exports = router;
It's because of process.env.DB_CONNECT in your code is undefined. Change line 5 of your src/backend/server.js file like below:
const dotenv = require('dotenv').config({ path: __dirname + '/.env' });
then comment dotenv.config()
and copy .env to src/backend/.
Or change line 10 or the file like this:
dotenv.config({ path: __dirname + '/.env' });
You have const User = require('../models/User'); two time in backend/routes/auth.js. Comment line 9. It will give you error.
I fixed it and created pull request in github. Merge it.
const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const app = express();
const cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/recart";
app.get("/", (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true }, async (err, db) => {
if (err) throw err;
var dbo = db.db("recart");
var result = await dbo.collection("users").find()
res.json(result.data)
});
})
app.listen(3001, ()=> {
console.log('App is running on port 3001');
})
Here I am trying to fetch data from mongodb using expressjs,
but in my browser nothing is coming.
No data is coming. But in my database there are documents.
Please have a look
const url = "mongodb://localhost:27017/recart";
Do you really need to provide collection's name here?
You can try:
const mongoUrl = 'mongodb://localhost:27017/'
const MongoClient = require('mongodb').MongoClient
app.get('/', async (req, res) => {
const client = await MongoClient.connect(mongoUrl, {
useNewUrlParser: true
})
const db = client.db("database_name")
const data = await db.collection("collection_name").find().toArray()
res.json(data)
}),
I am following a tutorial which uses mongo database with graphql, currently the tutor uses apollo-server v1 but I am using apollo-server v2, the problem I'm having is where do i make the connection of my models to graphql,
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config({ path: "variables.env" });
const Recipe = require("./models/Recipe");
const User = require("./models/User");
// Bring in GraphQL-Express middleware
const { graphiqlExpress, graphqlExpress } = require("apollo-server-express");
const { makeExecutableSchema } = require("graphql-tools");
const { typeDefs } = require("./schema");
const { resolvers } = require("./resolvers");
// Create schema
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
// Connects to database
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log("DB connected"))
.catch(err => console.error(err));
// Initializes application
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
credentials: true
};
app.use(cors(corsOptions));
// Create GraphiQL application
app.use("/graphiql", graphiqlExpress({ endpointURL: "/graphql" }));
// Connect schemas with GraphQL
app.use(
"/graphql",
bodyParser.json(),
graphqlExpress({
schema,
context: {
Recipe,
User
}
})
);
const PORT = process.env.PORT || 4444;
app.listen(PORT, () => {
console.log(`Server listening on PORT ${PORT}`);
});
so in apollo-server v1 you pass in your mongo schema (models) in graphqlExpress
Connect schemas with GraphQL
app.use(
"/graphql",
bodyParser.json(),
graphqlExpress({
schema,
context: {
Recipe,
User
}
})
);
but in v2 you no longer use graphqlExpress function,
https://www.apollographql.com/docs/apollo-server/v2/migration-two-dot.html
so how/where do i pass in my database models to?
currently I have this
const express = require ('express')
const mongoose = require ('mongoose')
const { ApolloServer } = require('apollo-server-express');
require('dotenv').config({path: 'variables.env'})
// mongo schemas/models
const Recipe = require('./models/Recipe')
const User = require('./models/User')
//Graphql schema
const {typeDefs} = require('./schema')
const {resolvers} = require('./resolvers')
// connects to database
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true} )
.then(()=> console.log('DB connected'))
.catch(error => console.log(error))
const PORT = process.env.PORT || 4444;
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
)
If you want to be exactly like you were before, you need to add the context function onto your ApolloServer init:
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
Recipe,
User
})
});
This example works perfect with PG, if you are using Mongo, just replace pg calls with mongoose and you should be good to go.