hello i'm trying to GET a book by his name from my db but when i execute the script the localhost shuts down and i have to restart. also i get the error :
ReferenceError: text is not defined
here is the server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
//display a specific product stored in database
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
Products.find(Products, req.param('name'), function(Products) {
if (!text) res.status(500).send("server error");
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
and the database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection('text').save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection('text').findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
What am i doing wrong?
not sure if there are other issues with the code. but with the error ReferenceError: text is not defined, might the compiler be complaining that they cannot determine where text was declared in the following lines?
apiRoutes.get('/book/:title', function (req, res) {
...
if (!text) res.status(500).send("Server error");
...
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
...
if (!text) res.status(500).send("server error");
...
if that is the error, you might need to replace text with req.body.text
Related
i export all the secret Api and password and cloudinary credentials to heroku using heroku config:set what syntax do i use now to replace process.env that i was using in development since i am not using .env file in the production. i am looking for syntax to replace the process.env
here is my code:
//----------------------------------------------------------------------------//
//--------------------------Dependencies For Route----------------------------//
//----------------------------------------------------------------------------//
var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
var NodeGeocoder = require('node-geocoder');
var multer = require('multer');
var async = require("async");
//Node Geocoder API Configuration
var options = {
provider: 'google',
httpAdapter: 'https',
apiKey: process.env.GEOCODER_API_KEY,
formatter: null
};
var geocoder = NodeGeocoder(options);
//Multer Storage
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
//Multer Filter
var imageFilter = function (req, file, cb) {
// accept image files only
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
//Storing Image + Filter
var upload = multer({ storage: storage, fileFilter: imageFilter});
//Cloudinary Configuration
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'dnposhqpc',
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});
// INDEX - SHOW ALL CAMPGROUNDS
router .get("/", function(req, res){
var perPage = 8;
var pageQuery = parseInt(req.query.page);
var pageNumber = pageQuery ? pageQuery : 1;
var noMatch = null;
if (req.query.search) {
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
// GET ALL CAMPGROUNDS FROM THE DB
Campground.find({"name": regex}, function(err, allCampgrounds){
if(err || !allCampgrounds){
console.log(err);
req.flash("error", "Something went wrong!");
} else {
if(allCampgrounds.length < 1){
noMatch = "No campground match that query, please try again.";
}
res.render("campgrounds/index", {campgrounds:allCampgrounds, page: 'campgrounds', noMatch: noMatch});
}
});
} else {
Campground.find({}).skip((perPage * pageNumber) - perPage).limit(perPage).exec( function(err, allCampgrounds){
Campground.count().exec(function (err, count) {
if(err) {
console.log(err);
} else {
res.render("campgrounds/index", {campgrounds:allCampgrounds, page: 'campgrounds', noMatch: noMatch,
campgrounds: allCampgrounds,
current: pageNumber,
pages: Math.ceil(count / perPage)
});
}
});
})
}
});
//----------------------------------------------------------------//
//-----------------CREATE NEW CAMPGROUNDS -----------//
//----------------------------------------------------------------//
//CREATE - ADD NEW CAMPGROUND TO DB
router.post("/", middleware.isLoggedIn, upload.single('image'), function(req, res){
// local variables
// Request The Name
var name = req.body.name;
// Request The Image
var image = req.body.image;
var imageId = req.body.imageId;
// Request The descriptions
var desc = req.body.descriptions;
// Request The Price
var price = req.body.price;
// Request The Author's ID + Username
var author = {
id: req.user._id,
username: req.user.username
};
//Location Code - Geocode Package
geocoder.geocode(req.body.location, function (err, data ) {
//Error Handling For Autocomplete API Requests
//Error handling provided by google docs -https://developers.google.com/places/web-service/autocomplete
if (err || data.status === 'ZERO_RESULTS') {
req.flash('error', 'Invalid address, try typing a new address');
return res.redirect('back');
}
//Error handling provided by google docs -https://developers.google.com/places/web-service/autocomplete
if (err || data.status === 'REQUEST_DENIED') {
req.flash('error', 'Something Is Wrong Your Request Was Denied');
return res.redirect('back');
}
// Error handling provided by google docs -https://developers.google.com/places/web-service/autocomplete
if (err || data.status === 'OVER_QUERY_LIMIT') {
req.flash('error', 'All Requests Used Up');
return res.redirect('back');
}
//Credit To Ian For Fixing The Geocode Problem - https://www.udemy.com/the-web-developer-bootcamp/learn/v4/questions/2788856
var lat = data[0].latitude;
var lng = data[0].longitude;
var location = data[0].formattedAddress;
//Reference: Zarko And Ian Helped Impliment the Image Upload - https://github.com/nax3t/image_upload_example
cloudinary.uploader.upload(req.file.path, function (result) {
//image variable needs to be here so the image can be stored and uploaded to cloudinary
image = result.secure_url;
imageId= result.public_id;
//Captures All Objects And Stores Them
var newCampground = {name: name, image: image, description: desc, price: price, author:author, location: location, lat: lat, lng: lng, imageId: imageId};
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err || !newlyCreated){
//Logs Error
req.flash('error', err.message);
return res.redirect('back');
} else {
//redirect back to campgrounds page
//Logs Error
console.log(newlyCreated);
//Flash Message
req.flash("success", "Campground Added Successfully");
//Redirects Back To Featured Campgrounds Page
res.redirect("/campgrounds");
}
});
});
});
});
// NEW - SHOW FORM TO CREATE NEW CAMPGROUND
router.get("/new", middleware.isLoggedIn, function(req, res) {
res.render("campgrounds/new");
});
// SHOW - SHOW ONLY ONE CAMPGROUND FROM THE DB
router.get("/:id", function(req, res) {
// find campround with the Provided id
Campground.findById(req.params.id).populate("comment").exec(function(err, foundcampground){
if(err || !foundcampground){
console.log(err);
req.flash("error", "Sorry, that campground does not exist!");
res.redirect("back"); // you need to redirect the user in case there isn't anything found by the provided id
} else {
console.log(foundcampground);
// render the show template
res.render("campgrounds/show", {campground: foundcampground});
}
});
});
// EDIT CAMPGROUND ROUTE
router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res) {
Campground.findById(req.params.id, function(err, foundcampground){
if(err || !foundcampground){
console.log(err);
req.flash("error", "campground not found");
return res.redirect("back");
}
res.render("campgrounds/edit", {campground: foundcampground});
});
});
//----------------------------------------------------------------//
//-----------------Update CAMPGROUNDS -----------//
//----------------------------------------------------------------//
// UPDATE CAMPGROUND ROUTE
router.put("/:id", middleware.checkCampgroundOwnership, upload.single('image'), function(req, res, next){
async.waterfall([
function(done) {
geocoder.geocode(req.body.campground.location, function (err, data) {
if (err || !data.length) {
req.flash('error', 'Invalid address');
return res.redirect('back');
}
done(null, data);
});
},
function(data, done) {
// handle image uploading
Campground.findById(req.params.id, function(err, foundCampground) {
if(err || !foundCampground) {
console.log(err);
req.flash("error", err.message);
return res.redirect("back");
} else {
done(null, foundCampground, data);
}
});
},
function(foundCampground, data, done) {
if(req.file) {
cloudinary.v2.uploader.destroy(foundCampground.imageId, function(err, result) {
if(err) {
req.flash("error", err.message);
return res.redirect("back");
} else {
done(null, foundCampground, data);
}
});
} else {
done(null, foundCampground, data);
}
},
function(foundCampground, data, done) {
// if new image uploaded, destroy the old one
if(req.file) {
cloudinary.uploader.upload(req.file.path, function(result) {
req.body.campground.imageId = result.public_id;
req.body.campground.image = result.secure_url;
done(null, foundCampground, data);
});
} else {
done(null, foundCampground, data);
}
},
function(foundCampground, data) {
// update
// var newCampground = {name: req.name, price: price, image: image, imageId: imageId, description: desc, author:author, location: location, lat: lat, lng: lng};
req.body.campground.lat = data[0].latitude;
req.body.campground.lng = data[0].longitude;
req.body.campground.location = data[0].formattedAddress;
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, campground){
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
req.flash("success","Successfully Updated!");
res.redirect("/campgrounds/" + campground._id);
}
});
}
], function(err) {
if (err) return next(err);
res.redirect('/campgrounds');
});
});
// DESTORY CAMPGROUND ROUTE
router.delete("/:id", middleware.checkCampgroundOwnership, function(req, res) {
Campground.findByIdAndRemove(req.params.id, function(err, foundcampground){
if(err || !foundcampground){
req.flash("error", "Something went wrong!");
res.redirect("/campgrouns");
} else {
req.flash("success", "You have successfully deleted a campground");
res.redirect("/campgrounds");
}
});
})
// Middleware
function escapeRegex(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
module.exports = router;
Thanks for your assistance
You use the same syntax.
For example, if I did:
heroku config:set EXAMPLE_NAME=sainteverest
then I can do the following:
console.log(process.env.EXAMPLE_NAME)
// sainteverest
Error: Can't set headers after they are sent. I hate this problem because get it many times and I though that I found my mistake,but I was wrong.
Okay this my code.
const mongoose = require ("mongoose");
const Spec = require("./specialist");
const Person = require("./person");
const Company = require("./company");
const bcrypt = require("bcryptjs");
module.exports.findUser=function(username,callback){
let query = {email_num:username};
Spec.findOne(query,(err_spec,spec_user)=>{
if(err_spec) throw err_spec;
if(!spec_user){
Person.findOne(query,(err_person,person_user)=>{
if(err_person) throw err_person;
if(!person_user){
Company.findOne(query,(err_company,company_user)=>{
if(err_company) throw err_company;
if(!company_user){
return console.log("Error User Not Found");
}
return callback(null,company_user);
});
}
return callback(null,person_user);
});
}
return callback(null,spec_user);
});
};
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, (err, isMatch) => {
if(err) throw err;
callback(null, isMatch);
});
};
module.exports.saveToken = function(username,role,token,callback){
let query = {email_num:username};
let updateToken={updatedToken:token};
if(role==="Person-User"){
Person.findOneAndUpdate(query,updateToken,callback);
}else if(role==="Specialist-User"){
Spec.findOneAndUpdate(query,updateToken,callback);
}else if(role==="Company-User"){
Company.findOneAndUpdate(query,updateToken,callback);
}else{
console.log("Something went goes wrong");
}
}
I've created 3 collections and this file for handling them all.
This is my main server code.
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const handlebars = require("express-handlebars");
const app = express();
const passport = require('passport');
const cookieParser = require("cookie-parser");
const config = require("./config/data");
const routes = require("./routes/users");
const company = require("./routes/company");
const person = require("./routes/person");
mongoose.Promise = global.Promise;
let options = {
useMongoClient: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 500,
poolSize: 10,
bufferMaxEntries: 0
};
mongoose.connect(config.database,options);
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log( `DB connected ${new Date()}...`);
});
//app.set('views',__dirname+'views');
app.engine('handlebars', handlebars({defaultLayout:false}));
app.set('view engine', 'handlebars');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
// app.use(cors());
app.use(cookieParser());
// Passport Middleware
// require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
app.get("/",(req,res)=>{
res.render("index");
});
// app.get("/forgotPass",(req,res)=>{
// res.render("forgotPass");
// });
app.get("/user", (req,res)=>{
res.render("user");
});
app.get("/login",(req,res)=>{
res.render("login");
});
app.get("/signup",(req,res)=>{
res.render("signup");
});
app.get("/we",(req,res)=>{
res.render("we");
});
app.get("/blog",(req,res)=>{
res.render("blog");
});
app.get("/contactUs",(req,res)=>{
res.render("contactUs");
});
app.get("/userAsApplicant",(req,res)=>{
res.render("userAsApplicant");
});
app.use("/users",routes);
app.use("/company",company);
app.use("/person",person);
app.get("/faq",(req,res)=>{
res.render("faq");
});
app.listen(config.port,()=>{
console.log(`Server running on port ${config.port}....`);
});
Also for many form handler I'm using Ajax for all requests.
$(function () {
$('.subForm').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/users/spec/register',
data: $(this).serialize(),
success:function(data){
if(data.success){
location.href="http://localhost:3000/login"
}else{
location.href="http://localhost:3000/signup"
}
}
});
e.preventDefault();
});
$('.personAuth').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/person/register',
data: $(this).serialize(),
success:function(data){
if(data.success){
location.href="http://localhost:3000/login"
}else{
console.log("Chexav");
location.href="http://localhost:3000/signup";
}
}
});
e.preventDefault();
});
$('.companyAuth').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/company/register',
data: $(this).serialize(),
success:function(data){
if(data.success){
location.href="http://localhost:3000/login"
}else{
location.href="http://localhost:3000/signup"
}
}
});
e.preventDefault();
});
$('.logInForm').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/users/authenticate',
data: $(this).serialize(),
success:function(data){
console.log(data);
if(data.token){
localStorage.setItem("Authorization",data.token);
$.ajax({
type:'get',
url:'http://localhost:3000/users/user',
beforeSend: function(xhr){xhr.setRequestHeader('auth', localStorage.getItem("Authorization"));},
success:location.href="http://localhost:3000/users/user"
})
}
}
});
e.preventDefault();
});
});
And this route for authentication.
const express = require("express");
const router = express.Router();
const Spec = require("../models/specialist");
const jwt = require("jsonwebtoken");
const config = require("../config/data");
const Model = require("../models/model");
//Registration route
router.post("/spec/register",(req,res)=>{
let date=new Date();
let newUser = new Spec({
name:req.body.spec_name,
email_num:req.body.spec_email,
password:req.body.spec_password,
role:"Specialist-User",
isActive:true,
created:date,
updatedToken:"JWT"
});
if(newUser.password===req.body.spec_confirmPass){
Spec.getUser(newUser.email_num,(error,user)=>{
if(error) throw error;
if(!user){
Spec.addUser(newUser,(err,user)=>{
if(err){
console.log("err");
res.json({success:false,msg:"Somethings Went Wrong"});
} else {
res.header("Content-Type","application/json");
res.json({success:true,msg:"User Registered"});
// res.redirect("/login");
}
});
}else{
res.json({success:false,msg:"User Already Exists"});
}
});
}else{
res.json({success:false,msg:"Password Not Confirmed"});
}
});
//Authentication route
router.post('/authenticate', (req, res,next) => {
const email = req.body.email;
const password = req.body.password;
console.log("UserData");
Model.findUser(email, (err, user) => {
console.log("UserData1");
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}
Model.comparePassword(password, user.password, (err, isMatch) => {
console.log("UserData2");
if(err) throw err;
if(isMatch){
let payload={
name:user.name,
email:user.email_num,
role:user.role,
deleted:user.deleted,
isActive:user.isActive,
created:user.created,
};
let token = jwt.sign(payload,config.JWT_SECRET,{
expiresIn:1440
});
Model.saveToken(email,user.role,token,(err,success)=>{
if(err) return err;
console.log("Success");
// res.setHeader('Authorization',token);
// res.cookie('Authorization',token);
res.json ({ success: true, token: token });
// res.redirect("/users/user");
});
} else {
return res.json({success: false, msg: 'Wrong password'});
}
});
});
// res.redirect("/user");
});
router.use(function(req, res, next) {
console.log(req.headers);
let token = req.body.token || req.headers['auth'] || req.query.token || req.cookies.Authorization;
// console.log(token);
if (token) {
jwt.verify(token, config.JWT_SECRET, function(err, decoded) {
if (err) {
console.log(err);
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
res.render("user");
}
});
} else {
return res.status(403).json({
success: false,
message: 'No token provided.'
});
}
});
router.get("/user", (req,res)=>{
res.render("user");
});
module.exports = router;
As template engine I'm using Handlebars.So with registration everything okay,but when I'm trying to authenticate server brings
Error: Can't set headers after they are sent.
I know that I can use cookies,but I want to keep away from that.
Sorry for language mistakes, and Thanks for help.
Error: Can't set headers after they are sent.
It means that you are sending multiple response to your client side.
I think you just need to delete your res.render("user"); in your last middleware like this :
router.use(function(req, res, next) {
console.log(req.headers);
let token = req.body.token || req.headers['auth'] || req.query.token || req.cookies.Authorization;
// console.log(token);
if (token) {
jwt.verify(token, config.JWT_SECRET, function(err, decoded) {
if (err) {
console.log(err);
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
// Go next and delete res
next();
// res.render("user");
}
});
} else {
return res.status(403).json({
success: false,
message: 'No token provided.'
});
}
});
Hope it helps.
i develop a new project for my school and i try to fetch some data from my database but i ecounter that error in my terminal:
ReferenceError: db is not defined
here are my files from my project:
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
db.products.find();
if (err) return next(err);
res.json(post);
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
// Start the server
app.listen(port);
console.log('http://localhost:' + port);
and database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
package.json:
{
"name": "firstapp",
"main": "server.js",
"dependencies": {
"bcrypt": "^0.8.5",
"body-parser": "~1.9.2",
"express": "~4.9.8",
"jwt-simple": "^0.3.1",
"mongoose": "~4.2.4",
"mongodb" : "~1.2.5",
"morgan": "~1.5.0",
"passport": "^0.3.0",
"passport-jwt": "^1.2.1"
}
}
Because db is not defined and you don't need it just use the model "products", just change this
apiRoutes.get('/productinfo' , function(req, res, next) {
db.products.find();
if (err) return next(err);
res.json(post);
});
To this
apiRoutes.get('/productinfo' , function(req, res, next) {
products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
i'm trying to get some data from the apiRoutes.get('/resources/productinfo/:name') and i have this error, i dont know whats going wrong... also the apiRoutes.get('/book/:title') doesnt seems to work! i dont know what am i doing wrong
UPDATED:
> TypeError: Cannot read property 'findOne' of undefined <br> at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26) <br>
> at /home/themis/firstapp/api/server.js:109:22 <br>
> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
> <br> at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
here is the server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!req.body.text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
access.findProductsByName(Products, req.param('name'), function(Products) {
if (!products) res.status(500).send("server error");
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
and the database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
and the package.json
{
"name": "firstapp",
"main": "server.js",
"dependencies": {
"bcrypt": "^0.8.5",
"body-parser": "~1.9.2",
"express": "~4.9.8",
"jwt-simple": "^0.3.1",
"mongoose": "~4.2.4",
"mongodb" : "~1.2.5",
"morgan": "~1.5.0",
"passport": "^0.3.0",
"passport-jwt": "^1.2.1",
"redis": "~0.10.1"
}
}
incorect syntax, you must read property of db.collection, but you call that. Example:
db.collection['products']!!!
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
For example
var object = {
'some_value': 'value',
'some_methid': function(){ return 'method result'}
}
You can read and set property 'some_value', for example:
object['some_value'] // return 'value'
object.some_value // return 'value'
// STEP 2
Ok, in your methods of database.js you pass db variable, but this is not of db instance, it is mongoose model, and you must write like this:
module.exports.findBookByTitle = function (model, title, callback) {
model.findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (model, name, callback) {
model.findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
You can only declare module.exports once in a file, so you should change:
In your database.js file:
module.exports.saveBook
to
exports.saveBook
and so on
Take a look at this: https://www.sitepoint.com/understanding-module-exports-exports-node-js/
in package.json folder find mongodb inside dependencies and update with these value:
"mongodb": "^2.2.33",
Then Run
npm install
again. That will solve your probem.
Make sure to add following to the scripts sectionin your package.json file
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js",
"debugger": "DEBUG=*:* npm run dev"
},
i'm trying to make an api which stores products and users!
at this time i want to make sure that the product which will be posted each has a unique Serial number and the code that will allow to have the same name, but i encouter the following error!
> TypeError: db.collection.find is not a function <br> at
> Object.module.exports.saveProductsignup
> (/home/themis/firstapp/api/config/database.js:14:19) <br>
> at /home/themis/firstapp/api/server.js:103:21 <br>
> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:312:12)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
server.js
var express = require('express'),
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl= 'mongodb://localhost:27017/firstapp';
var access = require('./config/database.js');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
//User authentication (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
//create posts about product (POST http://localhost:8080/api/createpost)
apiRoutes.post('/resources/createpost', function (req, res) {
if (!req.body.issue || !req.body.SN) res.status(400).send("Please give an issue and a S/N for the product");
else {
access.savePost(db, req.body.issue, req.body.SN, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Post Created");
});
}
});
apiRoutes.post('/resources/productsignup', function (req, res) {
if (!req.body.name || !req.body.serialnumber) res.status(400).send("Please give a name and a Serial number for the product");
else {
access.saveProductsignup(db, req.body.name, req.body.serialnumber, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Post Created");
});
}
});
//restricted log in (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
//demo Start
apiRoutes.delete('/resources/productinfo/:id', function(req, res, next) {
Products.findByIdAndRemove(req.params.id, req.body, function(err, post){
if (err) return next(err);
res.json(post);
});
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
access.findProductsByName(db, req.param('name'), function(info) {
if (!products) res.status(500).send("server error");
else res.status(200).send(info);
});
}
});
//demo End
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.savePost = function (db, issue, SN, callback) {
db.collection('posts').save({
issue: issue,
SN: SN
}, callback);
};
module.exports.saveProductsignup = function (db, name, serialnumber, callback) {
db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })
db.collection('products').save({
name: name,
serialnumber: serialnumber
}, callback);
};
module.exports.findProductsByName = function (model, name, callback) {
model.findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
You have a typo in database.js in module.exports.saveProductsignup:
db.collection.find({ "serialnumber" : { $exists : true, $ne : null } })
Should be:
db.collection('products').find({ "serialnumber" : { $exists : true, $ne : null } })