Today I try open my server, but it doesn't start
Full code - https://github.com/meln1337/error-proxy
app.js
const express = require('express')
const config = require('config')
const mongoose = require('mongoose')
const app = express()
app.use(express.json({extended: true}))
app.use('/api/auth', require('./routes/auth.routes'))
const PORT = config.get('port') || 5000
async function start () {
try {
await mongoose.connect('mongodb+srv://borys:1q2w3e4r5t6y7u8i#cluster0-puuhz.mongodb.net/app', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
app.listen(PORT, () => {
console.log(`App has been started on port ${PORT}...`)
})
} catch (e) {
console.log('Server error', e.message)
process.exit(1)
}
}
start()
config/default.json
{
"port": 5000
}
Does the server not start due to mongodb?
If not then why does the server not start?
I was able to run it, locally, with a few changes to "remove" missing files (i.e., changing your mongodb uri to a localhost thingy).
Have you checked your console? When I run it, I get (assuming I have config), TypeError: config.get is not a function. So unless I'm missing something, that's your first issue.
The second is that, for me, obviously the Mongodb instance won't work. I assume that's not true for you - you don't get error querySrv ENODATA - but that's worth checking too.
Finally, if your question is still about mongodb, why not remove that? Just comment out the await... bit, and see if the server starts?
Related
I'm trying to connect MongoDB Atlas to my application and ran into this error when trying to run the mongoose.connect(), which is located in db.js (last code in the question). process.env.MONGO_URI seems to be interpreted as undefined and not string, giving the following error: "MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string."
this is the my config.env, in which I copy pasted the MONGO_URI from the Atlas.
MONGO_URI = mongodb+srv://kpae:XXXX#practice.xujsvaf.mongodb.net/?retryWrites=true&w=majority
this is app.js, where I believe I set up the basics to run the program.
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
dotenv.config({ path: '.config/config.env' })
connectDB()
const app = express()
const PORT = process.env.PORT || 5000
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
)
this is db.js
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (err) {
//console.log('this is an error')
console.error(err)
process.exit(1)
}
}
module.exports = connectDB
I'm having trouble pinpointing where the bug lies in my code because it seems like my files are in the root folder and MONGO_URI looks like a string. Any help is appreciated.
Can you please try once like this in your env file?
MONGO_URI='mongodb+srv://kpae:XXXX#practice.xujsvaf.mongodb.net/?retryWrites=true&w=majority'
const express = require("express")
const app =express()
const mongoose =require("mongoose");
const cors=require('cors');
const FeedbackModel=require('./models/feedback')
app.use(express.json());
app.use(cors);
mongoose.connect("the url no prblm here")
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
the get method is working fine before after i was working on my
frontend it stoped working
app.get("/getfeedback",(req,res)=>{
FeedbackModel.find({},(err,result)=> {
if(err)
{res.json(err)
}
else
{res.json(result)
}
});
})
the app is working fine but if i call for any request the url keep on
loading without any response it just keeps on spinning
app.post("/addfeedback",async(req,res)=>{
const feedback=req.body;
const newFeedback= new FeedbackModel(feedback);
await newFeedback.save();
res.json(feedback);
})
app.listen(3001,()=>{`enter code here`
console.log("Server runs in port 3001");
});
You are using cors package incorrectly.
It has to be called and then it returns whatever value is necessary to the middleware.
Imagine a function that returns a function, the first has to be called to reach the second one.
Try this
app.use(cors());
I just want to know Why "Server is Connected" comes before the "Database is connected" in terminal of VScode in express app?
Here is my code
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const exercises = require("./routes/exercises");
const users = require("./routes/users");
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8000;
app.use(cors());
app.use(express.json());
mongoose.connect("mongodb+srv://#cluster0.lzvul.mongodb.net/my_database?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true");
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", () => {
console.log("Connected successfully");
});
app.listen(port , () => {
console.log(`Server is running on localhost:${port}`);
})
First, take care of your credentials, use the .env file just like you used it for storing the port.
Now, talking about what happened to your code.
The mongoose.connection function returns a Promise, which means, a peace of code that will run along side the rest of your code if you don't specify that you want to wait for it to respond back.
For this reason, the server starts running before the database is properly connected, it takes longer for your application to get in contact with mongodb servers than it takes for express to get running.
I strongly recommend you to have a look at the Promise documentation to understand it deeper.
Anyway a possible solution for know is to await for the mongoose connection to be stablished and just then start your server
...
/*
Assuming you've put your mongodb URI in the MONGO_URI variable
at the .env file
*/
mongoose.connect(process.env.MONGO_URI)
.then(() => {
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", () => {
console.log("Connected successfully");
});
app.listen(port , () => {
console.log(`Server is running on localhost:${port}`);
});
})
.catch((err) => {
console.log("Something went wrong with the database connection");
});
By using the .then method we are basically saying, we want to wait for this function to respond, and when it responds we want to execute this following function, where we call the rest of logic you wrote, server startup included.
That will make sure that the database initializes before the server and if something goes wrong with this process the server doesn't start.
I just want to deploy a simple node js application on heroku but it always throws me a request timeout error, I don't know why? Actually, first I tried with my main project but it didn't work then I try with some basic node js code, and after deploying I literally got shocked because it is also not working. Is this some problem related to the WebSockets library or I am doing wrong (Please let me know), I am tired of searching for a solution to this problem.
server.js
const Socket = require("websocket").server
const http = require("http")
const server = http.createServer((req, res) => {})
server.listen(process.env.PORT || 3000, () => {
console.log("Listening on port 3000...")
})
const webSocket = new Socket({ httpServer: server })
webSocket.on('request', (req) => {
const connection = req.accept()
console.log("open")
connection.on('message', (message) => {
const data = JSON.parse(message.utf8Data)
if(data.type == "message"){
console.log(data.mess);
connection.send(JSON.stringify(data))
}
})
})
Please help me to get out of this.
I am unable to connect to cloud mongodb with the following code. Can anyone please tell me whats wrong with this code?
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ${port}'));
There are multiple steps you should follow to be able to connect Mongo DB so first make sure that you created an account plus connecting to a cluster, while creating it you'll be provided with enough info to create a cluster take your time and read.
after doing that the code is very simple:
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://[ACCOUNT NAME]:[PASSWORD]#cluster0-sxlgp.gcp.mongodb.net/test?retryWrites=true&w=majority", { useNewUrlParser: true }
);
replace ACCOUNTNAME and PASSWORD with info you provided when you created your MongoDB account
This can be found in their documentation try taking your time reading the documentation.
I believe your code looks good the error you are getting TransientTransactionError is temporary please use events to handle your connection result
mongoose
.connect(db, { useNewUrlParser: true })
mongooose.connection.once('open', () => {
console.log('db connection success');
});
mongooose.connection.on('err', (err) => {
console.log('db connection failed');
});