On saving the code (Node JS), getting the error, 'Parsing error: Unexpected Token'
Note - Mongo connected
Tried adjusting the curly brackets and semicolon, still not working
What am I doing wrong?
Below is the code,
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
//connecting and creating a database
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//schema setup
var campgroundSchema = new mongoose.Schema({
name: String,
url: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create( {name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
function(err, campground){
if (err){
console.log(err);
}
else {
console.log("newly created campground");
console.log(campground);
}
});
var campgrounds = [
{name: "Jenny Lake", image:"https://farm2.staticflickr.com/1424/1430198323_c26451b047.jpg"},
{name: "RichardBH", image:"https://photosforclass.com/download/flickr-7626464792"},
{name: "CampAliBaba", image:"https://photosforclass.com/download/flickr-7121865553"},
{name: "CampAliBabaHai", image:"https://photosforclass.com/download/flickr-2770447094"},
{name: "CampAliBabaHaiYe", image:"https://photosforclass.com/download/flickr-2602356334"},
];
app.get("/", function(req, res){
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
app.post("/campgrounds", function(req, res){
var name = req.body.name
var image = req.body.image
var newcampground = {name: name, image: image}
campgrounds.push(newcampground);
res.redirect("/campgrounds");
});
app.get("/campgrounds/new" , function(req, res){
res.render("new.ejs");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("YelpCamp server started!");
});
Expected-
The file should save error-free in order to start the server and run the application
Actual-
Getting above mentioned error
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});// missing the closing brackets
});
you have miss the closing tag
On line 55, you should have an extra });
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, allCampgrouns){
if(err){
console.log(err)
}
else {
res.render("campgrounds", {campgrounds:allCampgrounds});
}
});
});
Related
I am trying to post data to the sever to be save into mongodb. Notice get request is working right but I couldnt post any data to mongodb database.
The main code:
// Tools to be used in the web development
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
Genre = require('./models/genre.js');
Book = require('./models/book.js');
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');
conn.on('error', err => console.error('mongodb connection error',
err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from
mongodb'));
// Routing to specific pages:
app.get('/', function(req, res){
res.send('Hello World');
});
app.get('/api/genres', function(req , res){
Genre.getGenres(function(err, genres){
if(err){
throw err;
}
res.json(genres);
})
});
app.post('/api/genres', function(req , res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
if(err){
throw err;
}
res.json(genre);
})
});
app.get('/api/books', function(req , res){
Book.getBooks(function(err, books){
if(err){
throw err;
}
res.json(books);
})
});
app.get('/api/books/:_id', function(req , res){
Book.getBookById(req.params._id, function(err, book){
if(err){
throw err;
}
res.json(book);
})
});
//Specify the listening port
app.listen(3666);
//Display the url on the termianl
console.log('Server Running On http://localhost:3666');
Genres
var mongoose = require('mongoose');
var genreSchema = mongoose.Schema({
name:{
type: String,
requires: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model('Genre', genreSchema);
module.exports.getGenres = function(callback, limit){
Genre.find(callback).limit(limit);
}
//add genre
module.exports.addGenre = function(genre, callback){
Genre.create(callback);
}
I post using postman app and once I press post I receive nothing and nothing be added to the database
Postman Procedure
Postman Procedure
and The database before and after the post procedure remain the same
enter image description here
Try this instead:
module.exports.addGenre = function(genre, callback){
Genre.create(genre, callback); // genre is object to be added, { name: "Name" } for example
}
I have this as configuration of my Express index.js:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var router = express.Router();
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'learn'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
router.get('/add', function (req, res, next){
res.render('add_costumer', {title: 'Update'});
});
router.post('/add', function (req, res){
var input = req.body;
var data = {
name : input.name,
email : input.email,
phone : input.number_phone
};
connection.query('INSERT INTO `test` SET ?', data, function(err,rows){
if(err) throw err;
console.log("Error inserting : %s ",err );
res.redirect('/');
});
});
router.get('/update', function (req, res, next){
res.render('update', {judul: 'Add'});
});
module.exports = router;
But still when I ask for req.body.something in my routes I get some error pointing Cannot read property 'name' of undefined. Here is an example of a route that uses req.body and this picture of the printing code :
output like this
Any clue?
It looks like you are requiring body-parser but not actually using it.
Depending on what kind of content you are accepting you should do:
app.use(bodyParser.json()); // where app is your express app
app.use(bodyParser.urlencoded({ extended: true});
I am creating creating a bookstore demo app in Node.js. I have ran into a little situation with the POST request for creating a genre. I've setup so the name of the genre must be required if not don't insert it to the database. But when I use Postman to POST to the url localhost:3000/api/genres with the JSON
{
"name": "TEST"
}
It throws an error
{
"error": "Genre validation failed"
}
When I remove the required field in the genreSchema it works but the name of the genre doesn't appear. Here is my code
Code:
genre.js
var mongoose = require("mongoose");
// Create a schema for genre
var Schema = mongoose.Schema;
var genreSchema = Schema({
name:{
type: String,
required: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model("Genre", genreSchema);
// Methods
// get genres
module.exports.getGenres = function(callback, limit) {
Genre.find(callback).limit(limit);
};
// add a new genre
// TODO: Not working in Postman ValidationError
module.exports.addGenre = function(genre, callback) {
Genre.create(genre, callback);
};
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Genre = require('./models/genre');
var Book = require('./models/book');
// Connect to mongoose
mongoose.connect("mongodb://localhost/bookstore");
var db = mongoose.connection;
app.get("/", function(req, res){
res.json({ error: "Please use /api/books or /api/genres" });
});
// GET /api/genres
app.get('/api/genres', function(req, res){
Genre.getGenres(function(err, genres){
if(err) {
res.json({error: err.message})
}
res.json(genres);
});
});
app.post('/api/genres', function(req, res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
if(err) {
res.json({
error: err.message
})
}
res.json(genre);
});
});
// GET /api/books
app.get('/api/books', function(req, res){
Book.getBooks(function(err, books){
if(err) {
res.json({error: err.stack})
}
res.json(books);
});
});
// GET /api/book/:id
app.get('/api/book/:_id', function(req, res){
Book.getBookById(req.params._id, function(err, book){
if(err) {
res.json({error: err.message})
}
res.json(book);
});
});
app.listen(3000, function(){
console.log("Running on port 3000!")
});
Have you tried console.log(req.body); inside your post route? I don't think you've setup body-parser as middleware so req.body is coming in empty and therefore not sending anything to your Genre.addGenre method.
I'm building an app in NodeJS/Express combined with Mongodb, where I want to be able to comment to a post but I keep getting a 404 not found.
I setup the models and routes in my server.js and also setup the 'ref' between the two but this is the response I keep getting:
And as you can see with the following, the 'capture' aka 'post' does actually exist:
Edit: Made some changes to my initial code with the answers that Zen gave me.
This is my code:
-server.js
// Init Express Web Framework
var express = require('express');
var app = express();
var path = require('path');
// Set view engine to EJS & set views directory
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, 'client', 'views'));
app.use(express.static(path.resolve(__dirname, 'client')));
// Database Connection
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
require('./server/routes/capture');
require('./server/routes/comment');
mongoose.connect(configDB.url);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: 'application/json'}));
// Main route
app.get('/', function(req, res){
res.render('index.html');
});
// API
var api = express.Router();
require('./server/routes/capture')(api);
require('./server/routes/comment')(api);
app.use('/api', api);
// Port Settings
app.listen(process.env.PORT || 3000, process.env.IP);
console.log('Listening on port ' + process.env.PORT);
-capture.js model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = Schema({
birdname: {type: String, required: true},
place: String,
userId: String,
author: String,
picture: Schema.Types.Mixed,
created_at: Date,
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});
module.exports = mongoose.model('Capture', captureSchema);
-capture.js route:
var Capture = require('../models/capture');
module.exports = function(router) {
router.post('/captures', function(req, res){
var capture = new Capture();
capture.birdname = req.body.birdname;
capture.place = req.body.place;
capture.userId = req.body.userId;
capture.author = req.body.author;
capture.picture = req.body.picture;
capture.created_at = new Date();
capture.save(function(err, data){
if(err)
throw err;
console.log(req.body);
res.json(data);
});
});
router.get('/captures', function(req, res){
Capture.find({}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures', function(req, res){
Capture.remove({}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
router.get('/captures/:id', function(req, res){
Capture.findOne({_id: req.params.id}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures/:id', function(req, res){
Capture.remove({_id: req.params.id}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
};
-capture.js model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = Schema({
birdname: String,
body: {type: String, required: true},
userId: {type: String, required: true},
author: {type: String, required: true},
created_at: Date,
capture: [{ type: Schema.Types.ObjectId, ref: 'Capture'}]
});
module.exports = mongoose.model('Comment', commentSchema);
-comment.js route:
var Comment = require('../models/comment');
module.exports = function(router) {
router.post('/captures/:capture/comments', function(req, res, next){
var comment = new Comment();
comment.birdname = req.body.birdname;
comment.body = req.body.body;
comment.userId = req.body.userId;
comment.author = req.body.author;
comment.created_at = new Date();
comment.capture = capture;
comment.save(function(err, comment) {
if (err) { return next(err); }
req.capture.comments.push(comment);
req.capture.save(function(err, capture) {
if (err) { return next(err); }
res.json(comment);
});
});
});
};
Any help is much appreciated..
Thanks
I would work with one route script, seeing that your comments are attached to the post.
You also have to add a Map logic to the route parameters for cature and comment.
Try the following:
var Capture = require('../models/capture');
var Comment = require('../models/comment');
module.exports = function(router) {
router.post('/captures', function(req, res){
var capture = new Capture();
capture.birdname = req.body.birdname;
capture.place = req.body.place;
capture.userId = req.body.userId;
capture.author = req.body.author;
capture.picture = req.body.picture;
capture.created_at = new Date();
capture.save(function(err, data){
if(err)
throw err;
console.log(req.body);
res.json(data);
});
});
router.get('/captures', function(req, res){
Capture.find({}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures', function(req, res){
Capture.remove({}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
// Map logic to route parameter 'capture'
router.param('capture', function(req, res, next, id) {
var query = Capture.findById(id);
query.exec(function (err, capture) {
if (err) { return next(err); }
if (!capture) { return next(new Error("can't find post")); }
req.capture = capture;
return next();
});
});
// Map logic to route parameter 'comment'
router.param('comment', function (req, res, next, id) {
var query = Comment.findById(id);
query.exec(function (err, comment) {
if (err) { return next(err); }
if (!comment) { return next(new Error("can't find comment")); }
req.comment = comment;
return next();
});
});
router.get('/captures/:id', function(req, res){
Capture.findOne({_id: req.params.id}, function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.delete('/captures/:id', function(req, res){
Capture.remove({_id: req.params.id}, function(err){
res.json({result: err ? 'error' : 'ok'});
});
});
router.post('/captures/:capture/comments', function(req, res, next){
var comment = new Comment();
comment.birdname = req.body.birdname;
comment.body = req.body.body;
comment.userId = req.body.userId;
comment.author = req.body.author;
comment.created_at = new Date();
comment.capture = req.capture;
comment.save(function(err, comment) {
if (err) { return next(err); }
req.capture.comments.push(comment);
req.capture.save(function(err, capture) {
if (err) { return next(err); }
res.json(comment);
});
});
});
};
The status code is 404. Apparently, no corresponding router is found. The problem is that you export an "init" function in comment.js route. When you require the comment router in server.js, nothing happens.
// API
var api = express.Router();
require('./server/routes/capture')(api);
// you have forgotten it
require('./server/routes/comment')(api);
app.use('/api', api);
BTW, there is no need putting capture into req.body when you're posting to '/captures/:capture/comments', since you can get :capture by using const capture = req.params.capture;.
I'm trying to print name and job of people after taking input from via a html form on the browser. The program also allows deletion and update of record through simple links on the same page. The program is, however, not working.
I even tried creating a "newapp" database (created in the server file) and filled it with some dummy values, the program still wont work!
Following is my node.js file
var express= require("express"),
http= require("http"),
bodyparser= require('body-parser'),
mongo= require("mongodb");
var app= express(),
db= new mongo.Db("newapp",
new mongo.Server("localhost", 27017),
{safe:true}, {auto_reconnect: true}),
people= db.collection("people");
app.use(bodyparser.urlencoded({extended: true}));
app.get("/", function(req, res){
people.find().toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
app.listen(3000);
My index.jade file is:
form(method="POST")
p Name:
input(type="text", name="name")
p Job:
input(type="text", name="job")
p: button Add
if(typeof(people)!=="undefined")
ul
each person in people
li
h2= person.name+ " ("+ person.job+ ")"
p
a(href="/update/#{person._id}") Update
a(href="/delete/#{person._id}") Delete
else
p No People
Any help is much appreciated. Thanks a lot!
The error was that I had not done db.open(...) anywhere in the program
Correct working code is:
var express= require("express"),
http= require("http"),
bodyparser= require("body-parser"),
mongo= require("mongodb");
var app= express(),
db= new mongo.Db("newapp", new mongo.Server("localhost", "27017"),
{safe:true}, {auto_reconnect: true});
app.use(bodyparser.urlencoded({extended: true}));
db.open(function(err, db){
if(err)
console.log(err);
people= db.collection("people");
app.get("/", function(req, res){
var cursor= people.find();
cursor.toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
app.get("/update/:id", function(req, res){
people.findOne({_id: new mongo.ObjectID(req.params.id)},
function(err, doc){
if(err)
throw err;
res.render("update.jade", {person: doc});
});
});
app.post("/update/:id", function(req, res){
people.update({_id: new mongo.ObjectID(req.params.id)},{
name: req.body.name,
job: req.body.job
}, function(err, item){
if(err)
throw err;
res.redirect("/");
});
});
app.get("/delete/:id", function(req, res){
people.remove({_id: new mongo.ObjectID(req.params.id)},
function(err){
if(err)
throw err;
res.redirect("/");
});
});
});
app.listen(3000, function(){
console.log("Now Listening on port: 3000");
});
The index.jade (in views folder) is:
form(method="POST")
p Name:
input(type="text", name="name")
p Job:
input(type="text", name="job")
p: button Add
if(people!==NULL)
ul
each person in people
li
h2= person.name+ " ("+ person.job+ ")"
p
a(href="/update/#{person._id}") Update 
a(href="/delete/#{person._id}") Delete
else
p No People
The update.js (in views folder) is:
form(method="POST")
p Name:
input(type="text", name="name", value="#{person.name}")
p Job:
input(type="text", name="job", value="#{person.job}")
p: button Update
please check this hope this will work..
var express= require("express"),
http= require("http"),
bodyparser= require('body-parser'),
var MongoClient = require('mongodb').MongoClient;
var connect = require('connect'),
var app= express(),
MongoClient.connect("mongodb://localhost:27017/newapp", function(err, db) {
if(err) { return console.dir(err); }
var people = db.collection('people');
app.use(bodyparser.urlencoded({extended: true}));
app.get("/", function(req, res){
people.find().toArray(function(err, docs){
if(err)
throw err;
res.render("index.jade", {people: docs});
});
});
app.post("/", function(req, res){
people.insert({name: req.body.name, job: req.body.job},
function(err, doc){
if(err)
throw err;
res.redirect("/");
});
});
});
app.listen(3000);