how to replace process.env.GEOCODER_API_KEY in the routes - node.js

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

Related

Async handling issue in nodejs

I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.
This is API code
var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');
const router = express.Router();
router.get("/:userId", (req, res, next) => {
let uid = req.params.userId;
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
if(!err) {
if(data && data.length > 0) {
var message = '';
if(data.u_password){
//var pass = data.u_password;
if(bcrypt.compare('123456', data.u_password)) {
// Passwords match
message = 'Passwords match';
} else {
// Passwords don't match
message = 'Passwords dont match';
}
}
res.status(200).json({
message:message,
});
} else {
res.status(200).json({
message:"User Not found."
});
}
}
});
});
database.js
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: '',
database: 'lost_and_found',
debug : false
});
function executeQuery(sql, callback) {
pool.getConnection((err,connection) => {
if(err) {
return callback(err, null);
} else {
if(connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
return callback(error, null);
}
return callback(null, results);
});
}
}
});
}
function query(sql, callback) {
executeQuery(sql,function(err, data) {
if(err) {
return callback(err);
}
callback(null, data);
});
}
module.exports = {
query: query
}
Response
{"message":""}
Please change the bcrypt.compare code to following code. It is a callback function:
bcrypt.compare('123456', data.u_password, function(err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message:message,
});
})
EDIT 1: Please update the method to following logic:
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
if (err) {
throw err;
}
if (data && data.length > 0) {
var message = '';
if (data.u_password) {
bcrypt.compare('123456', data.u_password, function (err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message: message,
});
})
}
res.status(200).json({
message: "User Not found."
});
}
res.status(200).json({
message: "User Not found."
});
});

NodeJS Cannot set headers after they are sent to the client

Edit: Thanks for your help everyone. I ended up completely rewriting the code using async await to be more readable. The issue no longer persists.
I've been getting the following error when I try to view my site's ecommerce cart at /cart:
Example app listening on port 8080
/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongodb/lib/utils.js:132
throw err;
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:500:11)
at ServerResponse.setHeader (_http_outgoing.js:507:3)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/controllers/cart.js:99:9
at Function.<anonymous> (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:3928:16)
at parallel (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:2078:12)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/parallel.js:35:9
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/once.js:12:16
at iteratorCallback (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/eachOf.js:52:13)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/onlyOnce.js:12:16
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/node_modules/async/internal/parallel.js:32:13
at apply (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/lodash/_apply.js:15:25)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/lodash/_overRest.js:32:12
at callbackWrapper (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:2047:11)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:3928:16
at model.$__save.error (/mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/mongoose/lib/model.js:343:7)
at /mnt/c/Users/Gernene/Documents/Programming/journal-supplies-co/node_modules/kareem/index.js:297:21
This error seems to be caused by the lines:
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
After looking at some similar issues, I am fairly sure the lines above are comming into conflict with these:
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
However, I'm not sure how to fix this issue and could be wrong.
Here's my full cart code:
module.exports = function(app){
// Dependencies and imported functions
const async = require('async');
const ObjectId = require('mongoose').Types.ObjectId;
const validate = require('../modules/validate');
const paypal = require('paypal-rest-sdk');
const cookie = require('cookie');
const path = require('path');
const appDir = path.dirname(require.main.filename);
const cartMod = require("../modules/cart");
const cartCount = cartMod.itemCount;
const crypto = require("crypto");
// DB
const Cart = require('../models/carts');
const CartItem = require('../models/cart_items');
const Discount = require('../models/discounts');
const Product = require('../models/products');
paypal.configure({
"host" : "api.sandbox.paypal.com",
"port" : "",
'mode': 'sandbox', //sandbox or live
'client_id': process.env.JSC_PAYPAL_CLIENT_ID,
'client_secret': process.env.JSC_PAYPAL_CLIENT_SECRET
});
const payPalPayment = (items, total) => {
return {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": appDir + "/success",
"cancel_url": appDir + "/cancel"
},
"transactions": [{
"item_list": { "items": items },
"amount": {
"currency": "USD",
"total": total
},
"description": "This is the payment description."
}]
};
};
const createPayPalPayment = (payment, req, res) => {
paypal.payment.create(payment, function(err, payment) {
if (err) {
throw err;
} else {
if(payment.payer.payment_method === 'paypal') {
req.paymentId = payment.id;
var redirectUrl;
for(var i = 0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
}
});
};
const displayCartItems = (res, cartId, cartCount, discount) => {
CartItem.find({cart: cartId}, function(err, cartItems) {
if (err) return next(err);
var products = [];
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) throw err;
products.push(product);
return next();
});
},
function(err) {
if (err) res.status(400).send("Could not display cart items");
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
}
);
});
};
const createCart = (req, res, next) => {
var token = crypto.randomBytes(20).toString("hex");
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
return next();
});
};
const checkCart = (req, res, next) => {
var token = req.cookies["cart_token"];
if (!token) {
createCart(res, res, next);
} else {
Cart.find({token: token}, function(err, cart) {
if (err || !cart) createCart(res, res, next);
return next();
});
}
};
const addCartItem = (cartId, productId, quantity) => {
CartItem.findOne(
{'product': productId, "cart": cartId},
function(err, item) {
if (err || !item) {
CartItem.create({
cart: cartId,
product: productId,
quantity: quantity
});
} else {
var newQuantity = item.quantity + parseInt(quantity);
CartItem.update(
{'_id': item._id},
{quantity: newQuantity},
function(err, item) {});
}
}
);
};
const updateCartItem = (res, id, quantity) => {
CartItem.findById(id, function(err, item) {
if (err || !item) throw err;
CartItem.update({_id: id}, {quantity: quantity}, function(err, item) {
res.send("Successfully updated cart item quantity.");
});
});
};
const deleteCartItem = (res, id) => {
CartItem.findById(id, function(err, item) {
if (err || !item) throw err;
CartItem.remove({_id: id}, function(err, item) {
res.send("Successfully deleted cart item.");
});
});
};
const cartIndex = (req, res, cartCount) => {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) throw err;
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
displayCartItems(res, cart._id, discount.percent, cartCount);
});
} else {
displayCartItems(res, cart._id, 0, cartCount);
}
});
};
app.get("/discount", function (req, res) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {cartCount: cartCount});
});
});
app.post("/discount", checkCart, function (req, res) {
var code = req.body["code"];
Discount.findOne({code: code}, function(err, discount) {
if (err || !discount) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {err: true, cartCount: cartCount});
});
} else {
var cartToken = req.cookies["cart_token"];
Cart.findOne({token: cartToken}, function(err, cart) {
if (err || !cart) throw err;
Cart.update(
{_id: cart._id},
{discount: discount._id},
function(err, cart) {
cartCount(req, res, function(req, res, cartCount) {
res.render("discount/index", {err: false, cartCount: cartCount});
});
}
);
});
}
});
});
app.get('/cart', checkCart, function (req, res, next) {
cartCount(req, res, cartIndex);
});
app.post('/cart', checkCart, function (req, res, next) {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) return next(err);
CartItem.find({cart: cart._id}, function(err, cartItems) {
if (err) return next(err);
var purchases = [];
var total = 0;
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) {
res.status(400).send("Could not find products");
} else {
var purchase = {};
purchase["name"] = product.name;
purchase["sku"] = product.name;
purchase["price"] = product.price;
purchase["currency"] = "USD";
purchase["quantity"] = cartItem.quantity;
purchases.push(purchase);
total += product.price * cartItem.quantity;
}
return next();
});
},
function(err) {
if (err) {
res.status(400).send("Could not display cart items");
} else {
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
var discountItem = {};
discountItem["name"] = "Discount";
discountItem["sku"] = "Discount";
discountItem["price"] = -1 * (total * discount.percent / 100);
discountItem["currency"] = "USD";
discountItem["quantity"] = 1;
purchases.push(discountItem);
total += discountItem.price;
var payment = payPalPayment(purchases, total);
createPayPalPayment(payment, req, res);
});
} else {
var payment = payPalPayment(purchases, total);
createPayPalPayment(payment, req, res);
}
}
}
);
});
});
});
app.post('/cart/confirm', checkCart, function (req, res, next) {
var cartToken = req.cookies["cart_token"];
Cart.find({token: cartToken}, function(err, cart) {
if (err || !cart) return next(err);
else {
CartItem.find({cart: cart._id}, function(err, cartItems) {
if (err) return next(err);
var products = [];
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) {
res.status(400).send("Could not find products");
} else {
products.push(product);
}
return next();
});
},
function(err) {
if (err) {
res.status(400).send("Could not display cart items");
} else {
executePayPalPayment(req);
res.render("cart/index", {
cartItems: cartItems,
products: products
});
}
}
);
});
}
});
});
app.post('/cart/add/:id', checkCart, function (req, res, next) {
var cartToken = req.cookies["cart_token"];
var productId = req.params.id;
var quantity = validate.sanitize(req.body[`quantity`]);
if (validate.isInt(quantity)) {
Product.findById(productId, function(err, product) {
if (err || !product) throw err;
Cart.findOne({token: cartToken}, function(err, cart) {
if (err || !cart) throw err;
addCartItem(cart._id, product._id, quantity);
res.send("Product added!")
});
});
}
});
app.post('/cart/update/:id', checkCart, function (req, res, next) {
var id = req.params.id;
var quantity = req.body["quantity"];
if (!validate.isInt(quantity)) throw err;
else if (quantity < 1) {
deleteCartItem(res, id);
} else {
updateCartItem(res, id, quantity);
}
});
app.post('/cart/delete/:id', checkCart, function (req, res, next) {
var id = req.params.id;
deleteCartItem(res, id);
});
}
const createCart = (req, res, next) => {
var token = crypto.randomBytes(20).toString("hex");
Cart.create({token: token, discount: null}, function(err, cart) {
if (err || !cart) throw err;
res.setHeader('Set-Cookie', cookie.serialize("cart_token", token, {
path: "/",
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
return next();
});
};
const cartIndex = (req, res, cartCount) => {
var token = req.cookies["cart_token"];
Cart.findOne({token: token}, function(err, cart) {
if (err || !cart) throw err;
if (cart.discount) {
Discount.findById(cart.discount, function(err, discount) {
if (err || !discount) throw err;
displayCartItems(res, cart._id, discount.percent, cartCount);
});
} else {
displayCartItems(res, cart._id, 0, cartCount);
}
});
};
app.get('/cart', checkCart, function (req, res, next) {
cartCount(req, res, cartIndex);
});
}
Essentially, I'm trying to check if the user has any cookies which could identify their cart and create a new cookie/cart if not. Also, I call cartCount to display the number of cart items at the top of each page.
I really appreciate any help! Please let me know if you need more information!
Edit:
Full app.js:
// Dependencies
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const path = require("path");
const pug = require("pug");
const session = require("express-session");
const validate = require("./modules/validate");
const cartMod = require("./modules/cart");
const cartCount = cartMod.itemCount;
const port = process.env.PORT || 8080;
// DB
const mongoURI = 'mongodb://localhost/db';
mongoose.connect(process.env.MONGODB_URI || mongoURI);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
// Connected!
});
app.set('trust proxy', 1)
app.set("views", __dirname + "/views");
app.set("view engine", "pug");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(__dirname + "/assets"));
app.use(session({
secret: process.env.JSC_SESSIONS_SECRET,
resave: true,
saveUninitialized: false
}));
// Routes
require("./controllers/cart")(app);
require("./controllers/categories")(app);
require("./controllers/discount")(app);
require("./controllers/nav_pages")(app);
require("./controllers/pages")(app);
require("./controllers/products")(app);
require("./controllers/users")(app);
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
cartCount(req, res, function(req, res, cartCount) {
res.render("errors/404", { cartCount: cartCount, url: req.url });
return;
});
}
});
app.listen(port, function() {
console.log("Example app listening on port " + port)
});
Add return if err or cart not exist in checkCart:
if (err || !cart) return createCart(res, res, next);
return next();
This error usually means that you called res.send() or res.end() or any of the methods that send a response to the frontend. These methods can only be called once, and after calling them you're expected not to interact with the response anymore (for example, you can't call res.setHeader if before that you called res.render.
This code:
async.eachSeries(cartItems,
function(cartItem, next) {
Product.findById(cartItem.product, function(err, product) {
if (err) throw err;
products.push(product);
return next();
});
},
function(err) {
if (err) res.status(400).send("Could not display cart items");
res.render("cart/index", {
cartItems: cartItems,
products: products,
cartCount: cartCount,
discount: discount
});
}
);
If there's an error (and res.render is fired), then you should not send information to the client anymore (because you already did). It looks like it failed for one of the cart items but you still keep interacting with the res object.
To fix the issue, avoid calling res after you've sent data to the client.

how to return a value or string from call back function in Nodejs, mongooose

I have a function that is inserting user credentials. I want to return value from a call back function...
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body);
res.send(result);
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
return 'Error occured during insertion..';
} else
{
return 'You have sign up successfully...';
}
});
}
I want to return the response as a string but it showing undefined. How should it be done?
var router = require('express').Router();
var User = require('../Models').users;
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){
}
else{
res.send(result)
}
});
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..');
} else
{
callback(null, newuser);
}
});
}
Use the callback i.e.
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
User.signUp(req.body,function(err,result){
res.send(result);
});
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj,callback) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
callback('Error occured during insertion..',null);
} else
{
callback(null,'You have sign up successfully...');
}
});
}
Because of async nature .. Try this:
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){}
else{res.send(result)}
});;
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..',null);
} else
{
callback (null, 'You have sign up successfully...');
}
});
}

CANNOT GET with mongodb and nodejs

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

Problems in integration of everyauth example with a simple login application

I am trying to use everyauth example for logging in with facebook. I printed the everyauth debug message which kind of shows that the authentication is performed successfully. However, the everyauth.loggedIn variable is not set. I am not sure why. I am actually having my code like this
I have a page which has the link to auth/facebook. When the user clicks on that link, the user is sent for facebook authentication and everything completes. However, when I check for everyauth.loggedIn it is always undefined
if(everyauth.loggedIn) {
console.log('The user has logged in');
}
The above is something that I am trying to check when there is request at the '/' url. This is after the facebook authentication has been performed. However, it always comes out to be undefined. Could it be because of local, global variable issue. I am passing the everyauth variable to several modules. Any suggestions will be appreciated
app.js(sets up the express application)
var exp = require('express');
var app = exp.createServer();
var conf = require('/path/example/conf')
var everyauth = require('everyauth');
everyauth.debug = true;
var usersById = {};
var nextUserId = 0;
function addUser (source, sourceUser) {
var user;
user = usersById[++nextUserId] = {id: nextUserId};
user[source] = sourceUser;
return user;
}
var usersByFbId = {};
var usersByTwitId = {};
everyauth.everymodule
.findUserById( function (id, callback) {
callback(null, usersById[id]);
});
everyauth
.facebook
.appId(conf.fb.appId)
.appSecret(conf.fb.appSecret)
.findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
return usersByFbId[fbUserMetadata.id] || (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));;
})
.redirectPath('/');
everyauth
.twitter
.consumerKey(conf.twit.consumerKey)
.consumerSecret(conf.twit.consumerSecret)
.findOrCreateUser( function (sess, accessToken, accessSecret, twitUser) {
return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));;
})
.redirectPath('/');
app.root = __dirname;
global.host = 'local.host';
require('./app/config')(app, exp, everyauth);
require('./app/server/router')(app,everyauth);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
config.js
module.exports = function(app, exp, everyauth) {
app.configure(function(){
app.set('views', app.root + '/app/server/views');
app.set('view engine', 'jade');
app.set('view options', { doctype : 'html', pretty : true });
app.use(exp.bodyParser());
app.use(exp.cookieParser());
app.use(exp.session({ secret: 'super-duper-secret-secret' }));
app.use(everyauth.middleware(app));
app.use(exp.methodOverride());
app.use(require('stylus').middleware({ src: app.root + '/app/public' }));
app.use(exp.static(app.root + '/app/server'));
app.use(exp.static(app.root + '/app/public'));
});
router.js
var CT = require('./modules/country-list');
var AM = require('./modules/account-manager');
var EM = require('./modules/email-dispatcher');
var mongodb = require('mongodb');
module.exports = function(app, everyauth) {
// main login page //
app.get('/', function(req, res){
console.log('Root page called');
// This is the problem area. everyauth.loggedIn always comes out undefined
if(everyauth.loggedIn) {
console.log('The user has logged in');
}
// check if the user's credentials are saved in a cookie //
if (req.cookies.user == undefined || req.cookies.pass == undefined){
res.render('login', { locals: { title: 'Hello - Please Login To Your Account'}});
} else{
// attempt automatic login //
AM.autoLogin(req.cookies.user, req.cookies.pass, function(o){
if (o != null){
req.session.user = o;
res.redirect('/dashboard');
} else{
res.render('login', { locals: { title: 'Hello - Please Login To Your Account' }});
}
});
}
});
app.post('/', function(req, res){
console.log('app called');
AM.manualLogin(req.param('user'), req.param('pass'), function(e, o){
if (!o){
res.send(e, 400);
} else{
req.session.user = o;
if (req.param('remember-me') == 'true'){
res.cookie('user', o.user, { maxAge: 900000 });
res.cookie('pass', o.pass, { maxAge: 900000 });
}
res.send(o, 200);
}
});
});
app.post('/feedback', function(req,res) {
var server = new mongodb.Server('localhost',27017, {auto_reconnect: true}, {safe:true});
var db = new mongodb.Db('clicker', server);
db.open(function(err, db) {
if(!err) {
db.collection('feedback', function(err, collection) {
var currentTime = new Date().getTime();
var feedback = {value:req.param('feedback'), datetime:currentTime};
collection.insert(feedback);
db.close();
});
}
});
res.send('ok', 200);
});
// logged-in user homepage //
app.get('/home', function(req, res) {
if (req.session.user == null){
// if user is not logged-in redirect back to login page //
res.redirect('/');
} else{
res.render('home', {
locals: {
title : 'Control Panel',
countries : CT,
udata : req.session.user
}
});
}
});
app.get('/dashboard', function(req, res) {
if (req.session.user == null){
// if user is not logged-in redirect back to login page //
res.redirect('/');
} else{
res.render('dashboard', {
locals: {
title : 'Dashboard',
countries : CT,
udata : req.session.user
}
});
}
});
app.post('/home', function(req, res){
if (req.param('user') != undefined) {
AM.update({
user : req.param('user'),
name : req.param('name'),
email : req.param('email'),
country : req.param('country'),
pass : req.param('pass')
}, function(o){
if (o){
req.session.user = o;
// udpate the user's login cookies if they exists //
if (req.cookies.user != undefined && req.cookies.pass != undefined){
res.cookie('user', o.user, { maxAge: 900000 });
res.cookie('pass', o.pass, { maxAge: 900000 });
}
res.send('ok', 200);
} else{
res.send('error-updating-account', 400);
}
});
} else if (req.param('logout') == 'true'){
res.clearCookie('user');
res.clearCookie('pass');
req.session.destroy(function(e){ res.send('ok', 200); });
}
});
// creating new accounts //
app.get('/signup', function(req, res) {
res.render('signup', { locals: { title: 'Signup', countries : CT } });
});
app.post('/signup', function(req, res){
AM.signup({
name : req.param('name'),
email : req.param('email'),
user : req.param('user'),
pass : req.param('pass'),
country : req.param('country')
}, function(e, o){
if (e){
res.send(e, 400);
} else{
res.send('ok', 200);
}
});
});
// password reset //
app.post('/lost-password', function(req, res){
// look up the user's account via their email //
AM.getEmail(req.param('email'), function(o){
if (o){
res.send('ok', 200);
EM.dispatchResetPasswordLink(o, function(e, m){
// this callback takes a moment to return //
// should add an ajax loader to give user feedback //
if (!e) {
// res.send('ok', 200);
} else{
res.send('email-server-error', 400);
for (k in e) console.log('error : ', k, e[k]);
}
});
} else{
res.send('email-not-found', 400);
}
});
});
app.get('/reset-password', function(req, res) {
var email = req.query["e"];
var passH = req.query["p"];
AM.validateLink(email, passH, function(e){
if (e != 'ok'){
res.redirect('/');
} else{
// save the user's email in a session instead of sending to the client //
req.session.reset = { email:email, passHash:passH };
res.render('reset', { title : 'Reset Password' });
}
})
});
app.post('/reset-password', function(req, res) {
var nPass = req.param('pass');
// retrieve the user's email from the session to lookup their account and reset password //
var email = req.session.reset.email;
// destory the session immediately after retrieving the stored email //
req.session.destroy();
AM.setPassword(email, nPass, function(o){
if (o){
res.send('ok', 200);
} else{
res.send('unable to update password', 400);
}
})
});
// view & delete accounts //
app.get('/print', function(req, res) {
AM.getAllRecords( function(e, accounts){
res.render('print', { locals: { title : 'Account List', accts : accounts } });
})
});
app.post('/delete', function(req, res){
AM.delete(req.body.id, function(e, obj){
if (!e){
res.clearCookie('user');
res.clearCookie('pass');
req.session.destroy(function(e){ res.send('ok', 200); });
} else{
res.send('record not found', 400);
}
});
});
app.get('/reset', function(req, res) {
AM.delAllRecords( );
res.redirect('/print');
});
app.get('*', function(req, res) { res.render('404', { title: 'Page Not Found'}); });
};
}
To enable the express helpers like everyauth.loggedIn you have to call:
everyauth.helpExpress(app);
I am not sure why your code doesn't work. I had an example which works correctly but it needs mongodb. Just pushed to github if you want to have a try.
link to github

Resources