I am a beginner and starting to learn MongoDB, NodeJS and Express by creating a simple blog project. I facing a problem as my data cannot be stored in my MongoDB event though my MongoDB connects properly. There may be a mistake in my coding in index.js. I try to fix it, but it does not store the information that I submit in the blog. Please help me. Thank you.
This is my code in index.js. You can see my full file in this link if you want to test it. enter link description here
This is my index.js
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/my_database',{useNewUrlParser: true})
const app = new express()
const ejs = require('ejs')
const BlogPost = require('./models/BlogPost')
app.set('view engine', 'ejs')
app.use(express.static('public'))
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
const { error } = require('console')
app.listen(4000, () => {
console.log('App listening on port 4000')
});
app.get('/',(req,res)=>{
res.render('index')
})
app.get('/about', (req, res) => {
res.render('about');
});
app.get('/contact', (req, res) => {
res.render('contact');
});
app.get('/post',(req,res)=>{
res.render('post')
})
app.get('/posts/new',(req,res)=>{
res.render('create')
})
app.post('/posts/store',(req,res)=>{
BlogPost.create(req.body,(error,blogpost)=>{
res.redirect('/');
});
});
This what it show in my MongoDB compass
enter image description here
I think the database connection URL is not correct .
You can use following code,
const mongoose = require('mongoose');
mongoose.connect(db_url,{ useNewUrlParser: true }, function (err) {
if (err) throw err; console.log('Successfully connected'); });
app.post('/posts/store',async (req,res)=>{
let blog = await BlogPost.create(req.body);
res.render('index',blog);
});
you can access the blog data inside the index file by blog variable
Related
I'm finding a page layout for node.js like laravel php have their Template for layout and it is perfect. I want to achieve it here in node.js and finally found this express-ejs-layouts but there is a problem in it that I cant see in their documentation the layout will wrap all of my pages specially my signin and signup page which have a different header and footer. How can we prevent express-ejs-layouts from wrapping my other page?
const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const server = require('http').createServer(app);
const expressLayouts = require('express-ejs-layouts');
// Set Database Connection
const connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'project_101'
});
connection.connect(function(error){
if(!!error) console.log(error);
else console.log('Database Connected!');
});
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressLayouts);
app.get('/',(req, res) => {
let sql = "SELECT * FROM uploads";
let query = connection.query(sql, (err, rows) => {
if(err) throw err;
res.render('index');
});
});
app.get('/signup', (req, res) => {
res.render('signup');
});
app.get('/signin', (req, res) => {
res.render('signin');
});
app.get('/unknown-user', (req, res) => {
res.render('unknown-user');
});
app.get('/profile', (req, res) => {
res.render('profile');
});
const port = process.env.PORT || 3000;
// Server Listening
server.listen(port, function () {
console.log('Server successfully running at: -',port);
});
Finally got the solution for the problem express-ejs-layouts
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
You just need to declare your page as a layout and set it to false.
app.set("layout signin", false);
and render the page together with the layout.
app.get('/signin', (req, res) => {
res.render('signin', { layout: 'signin' });
});
ez fix ⚡️
You can bypass the template by sending the file back.
res.sendFile(path, options, fn);
options and fn are optional.
I'm making a GridView in Node.js, But, It's Not connecting to Mongoose and Creating the DB. When I write
show dbs
In my Mongo Shell Then I don't get my Database Created.
This is my Code
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}`);
});
The database will be created when you will add a first document in the collection automatically.
I spend so much time looking at this.. I am just following udemy tutorial where instructor used exactly below.. BUT when I run it, req.body is empty EVEN though I am sending it from source(I tried from both nodeman and insomnia). I am just posting { "name":"test" }... and it's not getting the req.body...
I console logged just req and do not see the parm 'body'... Can someone please throw me some light here? SO furstrated
const express = require('express');
const app = express();
const port = 8002;
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
Try using body-parser for your req.body.
First install the dependency npm install body-parser and then try executing the below code:
const app = express();
const bodyParser= require('body-parser')
const port = 8002;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
For more documentation refer: body-parser-documentation
=====
UPDATE and ANSWER:
I apparently missed changing the GET to POST in Postman. Not surprisingly, that solved the problem. Thank you all for your suggestions.
=====
Using Traversy's Udemy MERN class, but running into an issue with router.post().
Calling router.get works fine. router.post returns a 404.
Not sure why that is. Here are the relevant files:
server.js:
const express = require("express");
const router = express.Router();
const connectDB = require("./config/db");
const app = express();
// connect DBase
connectDB();
// Init middleware
app.use(express.json({ extended: false }));
// #route POST api/users
// #desc Register user
// #access Public
router.post("/", (req, res) => {
console.log(req.body);
res.send("User route server.js");
});
// Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/posts", require("./routes/api/posts"));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
db.js
const mongoose = require("mongoose");
const config = require("config");
const db = config.get("mongoURI");
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true
});
console.log("Mongo DB Connected...");
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
users.js
const express = require("express");
const router = express.Router();
const { check, validationResult } = require("express-validator/check");
// #route GET api/users
// #desc Test route
// #access Public
router.post("/", (req, res) => {
res.send("post message");
});
module.exports = router;
POSTMAN OUTPUT: 404 Cannot GET /api/users
Totally confused. Thanks!
This problem could come from your filename : in your server.js you import a file named users and your file Users.js start by an uppercase letter.
Though my rendering path is correct when I hit http://localhost:4444/admin/posts/create it shows some error like
Error: Failed to lookup view "/admin/posts/create" in views directory "D:\node practise\CMS\views"
app.js file is like
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cms', { useNewUrlParser: true })
.then(db => {
console.log('MONGO CONNECTED!');
})
.catch(error => {
console.log('MONGO NOT CONNECTED!');
})
//making app to use static file
app.use(express.static(path.join(__dirname, 'public')));
//define template engine
app.set('view engine', 'handlebars');
//set default engine
app.engine('handlebars', exphbs({defaultLayout: 'home'}));
//load routes
const home = require("./routes/home/index");
const admin = require("./routes/admin/index");
const posts = require("./routes/admin/posts");
//use routes
app.use(home);
app.use("/admin", admin);
app.use("/admin/posts", posts);
//setting up server
app.listen(4444, () => {
console.log('Listening....');
});
I have posts.js that handles this route like
const express = require("express");
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
})
router.get('/', (req, res) => {
res.send('It works!');
})
router.get('/create', (req, res) => {
res.render('/admin/posts/create');
})
module.exports = router;
And I have my views folder structure as
What may be the cause of error? When I try to send response it works but when I try to render the view it shows error.
Can you try res.render('admin/posts/create');?
If the view folders is set properly like this: app.set('views', './views'), you should be able to resolve simple view name like res.render('myview') under ./views folder