When I post the new event, it is created and the sort function works properly as well but when I call the search function, I want it to compare it with both name and location but it doesn't compare with location. Is there any way to check both? Also after sorting or search when I want to create a new event, it gives me the below error. I am new to this. Help me with both the errors.
server.js
var express= require('express');
var bodyParser= require('body-parser');
var morgan = require('morgan');
var config=require('./config');
var app= express();
var mongoose=require('mongoose');
var lodash= require('lodash');
var underscore= require('underscore');
//var User=require('./database/user')
mongoose.connect('mongodb://localhost:27017/db',function(err){
if(err){
console.log(err);
}
else{
console.log("connected!");
}
});
//res.json({message:" " })
app.use(bodyParser.urlencoded({extended: true })); //if false then parse only strings
app.use(bodyParser.json());
app.use(morgan('dev'));//log all the requests to the console
var api=require('./app/routes/api')(app,express,underscore,lodash);
app.use('/api',api);
app.get('*',function(req,res){
// res.sendFile(__dirname + '/public/views/index.html');
}); // * means any route
app.listen(config.port,function(err){
if(err){
console.log(err);
}
else{
console.log("The server is running");
}
});
api.js
var User= require('../models/user');
var Event=require('../models/event');
var config=require('../../config');
var secret=config.secretKey;
module.exports=function(app,express,underscore,lodash) {
var api = express.Router();
// app.use()
api.post('/signup', function (req, res) {
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password
});
user.save(function (err) {
if (err) {
res.send(err);
return;
}
res.json({
message: 'User created!'
});
});
});
api.get('/users', function (req, res) {
User.find({}, function (err, users) {
if (err) {
res.send(err);
return;
}
res.json(users);
});
});
/* api.get('search',function(req,res){
search: req.body.search;
if(search==)
});*/
api.post('/eventfeed', function (req, res) {
var event = new Event({
name: req.body.name,
location: req.body.location,
description: req.body.description,
price: req.body.price,
rating: req.body.rating
});
event.save(function (err) {
if (err) {
res.send(err);
return;
}
res.json({
message: 'Event created!'
});
});
});
api.get('/event', function (req, res) {
Event.find({}, function (err, event) {
if (err) {
res.send(err);
return;
}
res.json(event);
});
});
api.get('/sortby_price', function (req, res) {
Event.find({}, function (err, events) {
if (err) {
res.send(err);
return;
}
var ascending = true;//change to false for descending
events.sort(function (a, b) {
return (a.price - b.price) * (ascending ? 1 : -1);
});
res.json(events);
});
});
api.get('/sortby_rating', function (req, res){
Event.find({}, function (err, events) {
if (err) {
res.send(err);
return;
}
var ascending = true;//change to false for descending
events.sort(function (a, b) {
return (a.rating - b.rating) * (ascending ? 1 : -1);
});
res.json(events);
});
});
api.post('/search', function (req, res) {
Event.find({'name':req.body.name},function (err, events) {
if (err)
return res.json(err);
else
res.json(events);
});
Event.find({'location':req.body.name},function (err, events) {
if (err)
return res.json(err);
else
res.json(events);
console.log("name is" + req.body.name);
});
});
return api;
}
error
http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (c:\Users\MY LAPY\WebstormProjects\Main\node_modules\express\lib\response.js:718:10)
at ServerResponse.send (c:\Users\MY LAPY\WebstormProjects\Main\node_modules\express\lib\response.js:163:12)
at ServerResponse.json (c:\Users\MY LAPY\WebstormProjects\Main\node_modules\express\lib\response.js:249:15)
at Query.<anonymous> (c:\Users\MY LAPY\WebstormProjects\Main\app\routes\api.js:209:25)
at c:\Users\MY LAPY\WebstormProjects\Main\node_modules\mongoose\node_modules\kareem\index.js:177:19
at c:\Users\MY LAPY\WebstormProjects\Main\node_modules\mongoose\node_modules\kareem\index.js:109:16
at process._tickCallback (node.js:355:11)
In your /api/search route, you are performing two Event.find()s in parallel and inside the callback for each of those, you're responding to the same http request.
So you need to either:
Have a third callback that is called only when both Event.find()s have completed, so you respond to the request only once there, OR
Perform the Event.find()s sequentially by placing one inside the callback of the other and only respond to the request inside the inner-most callback, OR
Only perform one Event.find() by using $or to check either field. For example:
api.post('/search', function (req, res) {
Event.find({
$or: [ {'name': req.body.name}, {'location': req.body.name} ]
}, function (err, events) {
if (err)
return res.json(err);
else
res.json(events);
});
});
Related
router.post('/doktorismiAra', function (req, res, next) {
var doktoradisoyadiA=req.body.doktoradisoyadi
console.log(doktoradisoyadiA);
sql.connect(dbTelefon, function (err) {
if (err)
console.log(err);
var sqlRequest = new sql.Request();
var sqlQery="SELECT * FROM doktorkayit WHERE doktoradisoyadi LİKE ?"+'%'+doktoradisoyadiA+'%';
sqlRequest.query(sqlQery, function(err,data){
if(err) console.log(err)
console.log(data);
console.table(data.recordset);
console.log(data.rowsAffected);
console.log(data.recordset[0]);
sql.close();
});
});
});
'''info: ErrorMessageToken {
name: 'ERROR',
event: 'errorMessage',
number: 4145,
state: 1,
class: 15,
message: "An expression of non-boolean type specified in a context where a condition is expected, near 'LİKE'.",
serverName: 'DESKTOP-Q6EC342\SQLEXPRESS',
procName: '',
lineNumber: 1
}
'''
router.post('/doktorismiAra', function (req, res, next) {
var doktoradisoyadiA=req.body.doktoradisoyadi;
console.log(doktoradisoyadiA);
sql.connect(dbTelefon, function (err) {
if (err)
console.log(err);
var sqlRequest = new sql.Request();
var sqlQery="SELECT * FROM doktorkayit WHERE doktoradisoyadi LIKE '%"+doktoradisoyadiA+"%' ";
sqlRequest.query(sqlQery, function(err,data){
if(err) console.log(err);
console.log(data);
console.table(data.recordset);
console.log(data.rowsAffected);
console.log(data.recordset[0]);
sql.close();
});
});
});
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
So I am trying out my code for updating and showing it to the user. Basically it is able to do what I need to do but after performing it I get this error
C:\Users\tester01_2\myproject\node_modules\mongodb-core\lib\cursor.js:174
throw err;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.header (
C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:725:10)
at ServerResponse.send
(C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:170:12)
at C:\Users\tester01_2\myproject\dbUpdate.js:13:14
at C:\Users\tester01_2\myproject\dbUpdate.js:28:5
at handleCallback (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:171:5)
at nextFunction (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:682:5)
at Cursor.next [as _next]
(C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:692:3)
at loop
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:694:8)
at _each
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:741:16)
This is my code
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
module.exports = {
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function(doc) {
return res.send('Record Found. Now updating this document...' +
itemDescrip + ' Record Updated. This is the new record ' + doc )
res.end();
db.close();
});
});
}
}
var updateRecord = function(db, req, callback) {
var cursor = db.collection('documents').find({'Item Description':
req.body.itemDescrip, 'Issued QTY': req.body.issueQty})
cursor.each(function(err,doc){
assert.equal(err, null);
if(doc != err){
console.log('Successfully queried');
console.log(doc);
callback(JSON.stringify(doc));
} else{
throw err;
}
});
db.collection('documents').updateMany(
{ 'Item Description': req.body.itemDescrip},
{
$set: { 'Issued QTY': req.body.issueQty }
},function(err, results) {
console.log(results);
console.log('Done');
console.log(results);
});
};
I think it has to do with my res due to all the threads I have seen being res being in a wrong position but I need to put my res.send there so that it can use doc. Is there any way to solve this problem? Thanks.
Firstly, you should remove return in front of res.send().
Secondly, in updateRecord function, the callback function shouldn't be called in a loop, it will execute multiple times. And you close the db before you execute updateMany.
If you want to send doc, you should use a temp array to hold the doc, and pass it to res when you finish all logics in updateRecord.
If I understand you correctly, following is my modification of your codes,
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany({ 'Item Description': req.body.itemDescrip }, {
$set: { 'Issued QTY': req.body.issueQty }
}, function(err, results) {
if (err) return callback(err);
console.log('Done');
console.log(results);
var cursor = db.collection('documents').find({
'Item Description': req.body.itemDescrip,
'Issued QTY': req.body.issueQty
});
var temp = [];
cursor.each(function(err, doc) {
if (err) {
return callback(err);
}
console.log('Successfully queried');
console.log(doc);
temp.push(JSON.stringify(doc));
});
callback(null, temp);
});
};
module.exports = {
postCollection: function(req, res) {
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
if(err) {
res.send(err);
res.end();
db.close();
return;
}
updateRecord(db, req, function(err, docs) {
if(err){
res.send(err);
}
else{
res.send(docs);
}
res.end();
db.close();
});
});
}
}
module.exports.validateUser = function (req, res) {
User.find({ 'username': req.body.username, 'password': req.body.password }, function (err, result) {
if (result.length) {
var gridfs = req.app.get('gridfs');
var readstream = gridfs.createReadStream({
_id: result[0]._doc.picture
});
req.on('error', function (err) {
res.send(500, err);
});
readstream.on('error', function (err) {
res.send(500, err);
});
// Just sends the file
//readstream.pipe(res);
res.send('This is incedible');
} else {
res.send(false);
}
});
};
Just after the user is validated I am getting the file associated with it. Further I want to send some data along with the fine in response. I've used multer and gridfs-stream. Is this achievable. If not, then does something looks fishy in this approach?
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