I'm new in node and mongo.
I'm trying to connect mongo db with my node server but this error appears.
Error:getaddrinfo ENOTFOUND locahost
[nodemon] app crashed - waiting for file changes before starting...
server.js
`const express = require('express');
require('colors');
const products = require('./data/products');
const dotenv = require('dotenv');
//dotenv config
dotenv.config();
const { connectDb } = require('./config/config')
connectDb();
const app = express();
app.get('/', (req, res) => {
res.send('<h1>Welcome to Node server</h1>')
})
app.get('/products', (req, res) => {
res.json(products);
})
app.get('/products/:id', (req, res) => {
const product = products.find(p => p.id === req.params.id);
res.json(product);
})
const PORT = 8080;
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${process.env.PORT}`.inverse.green)
})`
config.js
const mongoose = require('mongoose');
require('colors');
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
})
console.log(`MongoDB connected ${conn.connection.host}`.yellow)
} catch (error) {
console.error(`Error:${error.message}`.inverse.red);
process.exit(1);
}
};
module.exports = { connectDb }
.env
PORT = 8080
NODE_ENV = development
MONGO_URI = mongodb://locahost:27017/local
Related
I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
I'm a new learner express.js I want to test simple post and get operations with tdd mechanism. I created the test, route, index and db files but when I try to test POST method it gives me this error.
This is my routes/task.js
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
This is my test/task.js
let chai = require("chai");
const chaiHttp = require("chai-http");
const { send } = require("process");
let server = require("../index");
//Assertion Style
chai.should();
chai.use(chaiHttp);
describe('Tasks API', () => {
/**
* Test the POST Route
*/
describe('POST /api/task', () => {
it("It should POST a new task", () => {
const task = {task: "Wake Up"};
chai.request(server)
.post("/api/task")
.send(task)
.end((err, response) => {
response.should.have.status(201);
response.body.should.be.a('string');
response.body.should.have.property('id');
response.body.should.have.property('task');
response.body.should.have.property('task').eq("Wake Up");
response.body.length.should.be.eq(1);
done();
});
});
});
});
This is my db.js
var sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "db.sqlite"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.')
db.run(`CREATE TABLE IF NOT EXISTS todo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task text
)`,
(err) => {
if (err) {
// Table already created
console.log(err);
}
});
}
});
module.exports = db
And this is my index.js
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
The thing that I try to do is building a test case to test the post method. I think I couldn't built the correct relations the files.
Currently, just by doing a POST request to /api/task, the error will appear. That is because of these lines in index.js:
app.post('/api/task', (req, res) => {
res.status(201).send(req);
});
The req parameter is circular, hence cannot be JSON-stringified.
Solution
In routes/task.js export the router:
const express = require('express');
const router = express.Router();
router.post("/api/task", async (req,res) => {
try {
const task = await new Task(req.body).save();
res.send(task);
} catch (error) {
res.send(error);
}
})
// By adding this line you can export the router
module.exports = router
In index.js, include the routes/task.js file and pass it to app.use(...), also remove the now-obsolete /api/task route:
const connection = require('./db');
const express = require('express');
const app = express();
const cors = require("cors");
const taskRoutes = require("./routes/task")
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.use(taskRoutes)
app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = app;
This way we got rid of the circular structure stringifying and the tests should now pass.
Hi I'm new to coding currently trying to set up a connection to my server.
Getting an error message:
"TypeError: connectDB is not a function"
This is my db.js file
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
and this is my server.js file
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
Looking for some assistance I'm really new to coding so please forgive me if I posted wrongly.
check this out:
You are exporting mongoose from the db.js file. Try exporting the function connectDB you just created.
// between brackets just in case you need to export something else, ok?
module.exports = { connectDB }
Then import it like this:
const { connectDB } = require('./config/db')
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
module.exports = { connectDB }
const express = require('express')
const server = express()
const dotenv = require('dotenv')
const { connectDB } = require('./config/db')
const products = require('./seed/products')
dotenv.config()
connectDB()
const app = express()
server.get('/', (req, res) => {
res.send('API is running.........')
})
server.get('/api/products', (req, res) => {
res.json(products)
})
server.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id)
res.json(product)
})
const PORT = process.env.PORT || 5000
server.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} port ${PORT}`)
)
I'm trying to call my mongoDB API but it's giving me this error:
xhr.js:178 GET http://localhost:3000/api/products 404 (Not Found)
Here is how I call my API:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("/api/products");
setProducts(res.data);
setLoading(false);
console.log(res.data)
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
And here is my server.js:
const express = require("express"),
bodyParser = require('body-parser'),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
this is my database.config.js:
const mongoose = require("mongoose");
module.exports = (name) => {
mongoose
.connect(process.env.MONGODB_URI || `mongodb://localhost/${name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log(`Successfully connected to ${name}`))
.catch((err) => console.log(err));
};
How can I fix this problem?
Here is my github project if you want to look over my code:
https://github.com/nathannewyen/the-beuter
Anyone can help me I am new to node js and I am stuck with this error it return 404 not found when I am trying to visit http://localhost:5000/api/items on my postman..
this is the file items.js
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({date: -1})
.then(items => res.json(items))
});
router.post('/', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save().then(item => res.json(item));
});
module.exports = router;
this is the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
add a '/' before pathname in server.js
app.use('/api/items', items);
localhost:5000/api/items should work then
You need to make the following changes to your server.js
import your router module
const express = require('express');
const mongoose = require('mongoose');
const router = require('path of the router module');
const app = express();
app.use(express.json());
app.use(router); //to use your router
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('/api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
Try this:-
As I can see in the image of "vscode"
you have used router.get("/")
whereas in postman you are using URL for GET request as localhost:5000/api/items.
Either change your backend code to router.get("/api/items") or correct your postman request to localhost:5000/