So i am creating a RESTFul api for my application using Node.js
However it is starting to feel abit redundant and therefore i am wondering if i am doing it correctly.
So when ever i have a new model i do the following:
First i create a file equal to the table name in the database (lets take a table called team as an example):
// IMPORT ROUTES
// =============================================================================
module.exports = function (express, sequelize, router) {
router.route('/team');
var DataTypes = require("sequelize");
var crypto = require('crypto');
// on routes that end in /Teams
// ----------------------------------------------------
router.route('/api/team')
// create a Team (accessed at POST http://localhost:8080/api/Teams)
.post(function (req, res) {
var name = req.body.name; //bodyParser does the magic
var academy_id = req.body.academy_id;
var team = Team.build({name: name, academy_id: academy_id});
team.add(function (success) {
res.json({message: 'Team created!'});
},
function (err) {
res.status(err).send(err);
});
})
// get all the Teams (accessed at GET http://localhost:8080/api/Teams)
.get(function (req, res) {
var team = Team.build();
team.retrieveAll(function (Teams) {
if (Teams) {
res.json(Teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.status("Team not found").send('Team not found');
});
});
var Team = sequelize.define('team', {
id: DataTypes.INTEGER,
name: DataTypes.STRING,
academy_id: DataTypes.INTEGER
}, {
freezeTableName: true,
instanceMethods: {
retrieveAll: function (onSuccess, onError) {
Team.findAll({}, {raw: true})
.ok(onSuccess).error(onError);
},
retrieveById: function (Team_id, onSuccess, onError) {
Team.find({where: {id: Team_id}}, {raw: true})
.success(onSuccess).error(onError);
},
add: function (onSuccess, onError) {
var Teamname = this.name;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
Team.build({name: Teamname, name: password})
.save().ok(onSuccess).error(onError);
},
updateById: function (Team_id, onSuccess, onError) {
var id = Team_id;
var Teamname = this.Teamname;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
Team.update({Teamname: Teamname, password: password}, {where: {id: id}})
.success(onSuccess).error(onError);
},
removeById: function (Team_id, onSuccess, onError) {
Team.destroy({where: {id: Team_id}}).success(onSuccess).error(onError);
},
retrieveByAcademyId: function(academy_id, onSuccess, onError)
{
Team.findAll({where: {academy_id: academy_id}}, {raw: true})
.ok(onSuccess).error(onError);
}
}
}
),
academy = sequelize.define('academy', {
id: DataTypes.INTEGER,
name: DataTypes.STRING,
organization_id: DataTypes.INTEGER,
status_id: DataTypes.INTEGER
});
Team.belongsTo(academy,{foreignKey: 'academy_id'});
// on routes that end in /Teams/:Team_id
// ----------------------------------------------------
router.route('/api/team/:team_id')
// update a Team (accessed at PUT http://localhost:8080/api/Teams/:Team_id)
.put(function (req, res) {
var team = Team.build();
team.name = req.body.name;
team.academy_id = req.body.academy_id;
team.updateById(req.params.id, function (success) {
console.log(success);
if (success) {
res.json({message: 'Team updated!'});
} else {
res.send(401, "Team not found");
}
}, function (error) {
res.send("Team not found");
});
})
// get a Team by id(accessed at GET http://localhost:8080/api/Teams/:Team_id)
.get(function (req, res) {
var team = Team.build();
team.retrieveById(req.params.team_id, function (teams) {
if (teams) {
res.json(teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
})
// delete a Team by id (accessed at DELETE http://localhost:8080/api/Teams/:Team_id)
.delete(function (req, res) {
var team = Team.build();
team.removeById(req.params.id, function (teams) {
if (teams) {
res.json({message: 'Team removed!'});
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
});
router.route('/api/academyTeam/:academy_id')
.get(function (req, res) {
var team = Team.build();
team.retrieveByAcademyId(req.params.academy_id, function (teams) {
if (teams) {
res.json(teams);
} else {
res.status(401).send("Team not found");
}
}, function (error) {
res.send("Team not found");
});
});
return router;
};
Then afterwards i add the following line to my server.js:
app.use(team_model);
then i repeat the action for the next table.
Am i doing it right or is there a way to optimize things?
Related
I have created 2 Users(Admin and Users) and also i have created many ToDos for a User but here my Todo array is empty in my User Schema. Unable to understand why todo task are not assigned to the User Schema.
UserSchema
var userSchema = new Schema({
name: {
type: String,
required: true,
maxlength: 30,
trim: true
},
role: {
type: Number,
default: 0
},
todos: [{
type: Schema.Types.ObjectId,
ref:"Todo"
}]
});
module.exports = mongoose.model("User", userSchema)
Todo Schema
let Todo = new Schema({
todo_heading: {
type: String
},
todo_desc: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
},
user: {
type: Schema.Types.ObjectId,
ref:"User"
}
})
module.exports = mongoose.model('Todo', Todo);
here are my routes
User Route
router.get("/user/:userId/todos", isSignedIn, isAuthenticated, getToDos)
Todo Route
router.get("/", getTodos)
router.get("/:id", getUsertodos);
router.post("/user/:userId/add", addUsertodos);
User Controllers
exports.getToDos = (req, res) => {
User.find({ _id: req.params._id })
.populate("todos")
.exec((err, toDo) => {
if (err) {
res.json(err)
}
res.json(toDo)
})
}
ToDo Controllers
exports.addUsertodos = (req, res) => {
let todo = new Todo(req.body)
todo.save((err, todo) => {
if (err) {
return res.status(400).json({
error: "not saved"
})
}
else {
return res.json(todo)
}
})
}
it should work as expected if you add the objectId of newly created todo to the todos property when you create a user.
//routers/todo.js
var express = require('express');
var router = express.Router();
const Todo = require('../models/Todo');
const User = require('../models/User');
/* GET home page. */
router.get('/', async function (req, res) {
let todos = await Todo.find();
res.json({
todos
});
});
router.post('/todos', async function (req, res) {
//add todos
let {
todo_desc,
todo_heading,
todo_priority,
todo_completed
} = req.body;
try {
//NOTE: for simplicity assigning first user but you can grab it from the params
let user = await User.findOne();
let todo = await Todo.create({
todo_desc,
todo_completed,
todo_priority,
todo_heading,
user: user._id
})
res.json({
message: 'todo created successfully',
todo
});
} catch (err) {
return res.status(500).json({
message: 'Unable to create a todo',
err: JSON.stringify(err)
})
}
});
module.exports = router;
Here is the user route where post route get the string id of created ID and converts it to ObjectId(), assign it to the todos.
var express = require('express');
var router = express.Router();
let _ = require('lodash');
var mongoose = require('mongoose');
const User = require('../models/User');
/* GET users listing. */
router.post("/", async function (req, res) {
let {
name,
todos
} = req.body;
try {
let user = new User();
user.name = name;
let objectIds = todos.split(',').map(id => mongoose.Types.ObjectId(id));
user.todos.push(...objectIds)
await user.save()
console.log("user: ", JSON.stringify(user));
if (_.isEmpty(user)) {
res.status(500).json({
message: 'unable to create user'
})
}
res.json(user);
} catch (err) {
res.status(500).json({
message: 'unable to create user',
err: JSON.stringify(err)
})
}
});
router.get("/", async function (req, res) {
try {
let user = await User.find().populate('todos');
console.log("user: ", JSON.stringify(user));
if (_.isEmpty(user)) {
res.status(500).json({
message: 'unable to find user'
})
}
res.json(user);
} catch (err) {
res.status(500).json({
message: 'unable to find user',
err: JSON.stringify(err)
})
}
});
module.exports = router;
Check out the attached screenshot, the user record now contains the todos assigned to it.
If you want checkout the working code, please visit this repo that i created!!.
Hope this help.Cheers!!
I have to implement a express web application to use rest services with mongodb.
my DBConfig.js file is like below which include my db schema,
var Mongoose = require("mongoose");
const Schema = Mongoose.Schema;
const UserSchema = new Schema({
name : {
type: String,
require: true
},
address : {
type: String,
require: false
},
password: {
type: String,
require: true
}
});
Mongoose.model('User', UserSchema);
Mongoose.connect("mongodb://localhost:27017/demo", function (err) {
if (err) {
console.log(err);
process.exit(-1);
}
console.log("Connected");
});
module.exports = Mongoose;
all the relevant methods are implement in my Controller.js file
var Mongoose = require("../DBSchema/DBConfig");
var UserSchema = Mongoose.model('User');
var Controller = function() {
this.insertUser = function (data) {
return new Promise(function(resolve, reject) {
var User = new UserSchema({
name: data.name,
address: data.address,
password: data.password
});
User.save().then(function () {
resolve({status: 200, message: "User inserted successfully"})
}).catch(function (err) {
reject({status: 500, message: "Error:- " + err})
});
});
}
this.getAll = function () {
return new Promise(function (resolve, reject) {
UserSchema.find().exec().then(function (data) {
resolve({status: 200, Userdata: data})
}).catch(function (err) {
resolve({status: 500, message : "No data available"})
})
})
}
this.getuser = function (id) {
return new Promise(function (resolve, reject) {
UserSchema.find({_id: id}).exec().then(function (data) {
resolve({status: 200, userSearched: data});
}).catch(function (err) {
reject({status: 404, message: "User NOT FOUND"});
})
})
}
this.updateUser = function (id, data) {
return new Promise(function (resolve, reject) {
UserSchema.update({_id: id}, data).then(function (data) {
resolve({status: 200, message: "User updated successfully"})
}).catch(function (err) {
reject({status: 500, message: "Error:- " + err})
})
})
}
this.remove = function (id) {
return new Promise(function (resolve, reject) {
UserSchema.remove({_id: id}).then(function () {
resolve({status: 200, message: "Successfully deleted"})
}).catch(function (err) {
resolve({status: 500, message: "Error : "+err})
})
})
}
}
module.exports = new Controller();
now I have to call my rest services,I want to know how can I use these methods which are in my controller to access data.
I'm using postman to view my data.
the output should be
{
"data": [
{
"_id": "5cf724a58c9b061ba062a28c",
"name": "name1",
"address": "adress1",
"password": "password1",
"__v": 0
}
]
}
All you need is you have to define the routes in your URL to access relevant method, example I create a file called User.Routes.js under a folder called UserController which you can add your Controller.js file also to arrange in an order to get a clear idea. and also assume you add your DBConfig.js file under folder called DBSchema, which made you to do good code practise.
var Express = require('express');
var router = Express.Router();
var Controller = require('./Controller')
router.get('/',function (req,res) {
Controller.getAll().then(function (data) {
res.status(data.status).send({data:data.Userdata})
});
});
router.get('/:id',function (req,res) {
Controller.getuser(req.params.id).then(function (data) {
res.status(data.status).send({data:data.userSearched});
});
});
router.post('/',function(req,res){
Controller.insertUser(req.body).then(function (data) {
res.status(data.status).send({message: data.message});
}).catch(function (err) {
res.status(err.status).send({message: err.message});
});
});
router.put('/:id',function (req,res) {
Controller.updateUser(req.params.id,req.body).then(function (data) {
res.status(data.status).send({message: data.message});
});
});
router.delete('/:id', function (req,res) {
Controller.remove(req.params.id).then(function (data) {
res.status(data.status).send({message: data.message});
});
});
module.exports = router;
and now you need to use methods in your User.Routes.js via postman. for that you need to give url name to be accessed. example, I create Routes.js file
const Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./UserController/User.Route');
Routes.use('/user/', UserRoute);
module.exports = Routes;
like this if you want to view data from your schema you have to add the url like -"http://localhost:8083/user"
and your app.js file want to require the created Routes file for that you can do like,
const Express = require("express");
const app = Express();
const BodyParser = require("body-parser");
const Routes = require("./Routes");
app.use(BodyParser.json());
app.use("/", Routes);
app.listen(8083, "localhost", function(err) {
if (err) {
console.log(err);
process.exit(-1);
}
console.log("Server listening on port 8083");
});
Now using postman you can add user,update and delete particular user by giving user id in your URL like - "http://localhost:8083/user/5cf724a58c9b061ba062a28c"
I am trying to incorporate the express-jwt library and I do not quite understand how it's error handling works.
The documentation says:
Error handling
The default behavior is to throw an error when the token is invalid, so you can >add your custom logic to manage unauthorized access as follows:
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).send('invalid token...');
}
});
But I am confused how that works. If I have a simple req res situation, and I want to call next if the token is valid, or call next with an error if it is not, where to I put that app.use function?
For instance, here is my code:
router.post('/', expressJwt({
secret: jwtSecret,
credentialsRequired: false
}), (req, res, next) => {
databaseController.findUser(req.user.email, (err, user) => {
if (err) {
return next(err)
}
res.json(user)
})
})
The err here would come from my DB call, not from the express-jwt validation.
Any help is appreciated.
Another way is you could place the middleware with app.use to scan all the routes for a valid jwt in the header or the query string.
Any public endpoints can be exempted using the unless keyword.
Ex:
app.use(expressjwt({credentialsRequired: true, secret: config.TOKEN_SECRET, requestProperty: 'user'}).unless({path: config.PUBLIC_URLs}));
app.use(function(err, req, res, next) {
if(err.name === 'UnauthorizedError') {
res.status(err.status).send({message:err.message});
logger.error(err);
return;
}
next();
});
this is my solution for individual routes.
function UseJwt(){
return [
jwtExpress({ secret: configuration.jwtSecret, algorithms: ['HS256'] }),
function(err, req, res, next){
res.status(err.status).json(err);
}
]
}
usage...
app.get(`/${prefix}/:user_id`,
...UseJwt(),
async function (req, res) {
// handle your code here.
}
)
You can create an express middleware just before the code you use to start express server.
// Global error handler that takes 4 arguments and ExpressJS knows that
app.use((err, req, res, next) => {
res.status(err.status).json(err);
});
app.listen(3000);
I use that for apps use REST but you can use the same approach and modify what should happen based on your needs. If you use Jade template for instance then you need to populate the template with the data you want to show to end user and log the rest on your log file.
app.use((err, req, res, next) => {
res.locals.status = status;
res.render('error')
});
Express-jwt is just a method that returns a RequestHandler (a function that takes in req, res, and next). This RequestHandler can be wrapped in a closure that replaces its next input with one you design that handles or formats errors. For example:
/**
* Wraps an Express request handler in an error handler
* #param method RequestHandler to wrap
* #returns RequestHandler
*/
export function formatError<T extends RequestHandler>(method: T): RequestHandler {
return async (req, res, next) => {
const wrapError = (err: any) => {
return (err)
? res.status(err.status).send({ message: err.message })
: next();
};
await method(req, res, wrapError);
};
}
const jwtMiddleware = formatError(expressjwt(...));
Then just use this closure instead of using expressjwt() directly:
router.post('/', jwtMiddleware, ...);
import { Schema, model } from "mongoose";
export const ROLES = ["Admin", "Estudiante","Docente","Secretario","Vicerrector","Inpector"];
const roleSchema = new Schema(
{
name: String,
},
{
versionKey: false,
}
);
export default model("Role", roleSchema);
//
import { Schema, model } from "mongoose";
import bcrypt from "bcryptjs";
const productSchema = new Schema(
{
username: {
type: String,
unique: true,
},
email: {
type: String,
unique: true,
},
password: {
type: String,
required: true,
},
//********************************NUEVOS CAMPOS PARA USUARIOS ADMINISTRADORES
nombres: {
type: String,
required: true,
},
apellidos: {
type: String,
required: true,
},
cedula: {
type: String,
unique: true,
},
foto: {
type: String,
required: true,
},
status: {
type: String,
required: true,
},
telefono: {
type: String,
required: true,
},
//---------------TIPO DE DOCUMENTOS
typo:{
type: String,
},
//---------------TIPO MAS DATOS
roles: [
{
type: Schema.Types.ObjectId,
ref: "Role",
},
],
},
{
timestamps: true,
versionKey: false,
}
);
productSchema.statics.encryptPassword = async (password) => {
const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(password, salt);
};
productSchema.statics.comparePassword = async (password, receivedPassword) => {
return await bcrypt.compare(password, receivedPassword)
}
export default model("User", productSchema);
//
import Role from "../models/Role";
import User from "../models/User";
import bcrypt from "bcryptjs";
export const createRoles = async () => {
try {
// Count Documents
const count = await Role.estimatedDocumentCount();
// check for existing roles
if (count > 0) return;
// Create default Roles
const values = await Promise.all([
new Role({ name: "Estudiante" }).save(),//user
new Role({ name: "Docente" }).save(),//moderator
new Role({ name: "Admin" }).save(),//admin
new Role({ name: "Secretario" }).save(),//-------+++
new Role({ name: "Vicerrector" }).save(),//-------+++
new Role({ name: "Inpector" }).save(),//-------+++
]);
console.log(values);
} catch (error) {
console.error(error);
}
};
export const createAdmin = async () => {
// check for an existing admin user
const user = await User.findOne({ email: "10004095632w#gmailcom" });
// get roles _id
const roles = await Role.find({ name: { $in: ["Admin", "Estudiante","Docente","Secretario","Vicerrector","Inpector"] } });
if (!user) {
// create a new admin user
await User.create({
username: "admin",
email: "10004095632w#gmail.com",
password: await bcrypt.hash("Imperio 789.", 10),
roles: roles.map((role) => role._id),
nombres: "ad",
apellidos: "ad",
cedula: "123456789",
foto: "profile.jpg",
status: "Activo",
telefono: "+570995283857",
});
console.log('Admin User Created!')
}
};
//
import jwt from "jsonwebtoken";
import config from "../config";
import User from "../models/User";
import Role from "../models/Role";
export const verifyToken = async (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) return res.status(403).json({ message: "No token provided" });
try {
const decoded = jwt.verify(token, config.SECRET);
req.userId = decoded.id;
const user = await User.findById(req.userId, { password: 0 });
if (!user) return res.status(404).json({ message: "No user found" });
next();
} catch (error) {
return res.status(401).json({ message: "Unauthorized!" });
}
};
export const isSecretario = async (req, res, next) => {
try {
const user = await User.findById(req.userId);
const roles = await Role.find({ _id: { $in: user.roles } });
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "Secretario") {
next();
return;
}
}
return res.status(403).json({ message: "Require Moderator Role!" });
} catch (error) {
console.log(error)
return res.status(500).send({ message: error });
}
};
export const isAdmin = async (req, res, next) => {
try {
const user = await User.findById(req.userId);
const roles = await Role.find({ _id: { $in: user.roles } });
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "Admin"||roles[i].name === "Secretario") {
next();
return;
}
}
return res.status(403).json({ message: "Require Admin Role!" });
} catch (error) {
console.log(error)
return res.status(500).send({ message: error });
}
};
//
import User from "../models/User";
import { ROLES } from "../models/Role";
const checkDuplicateUsernameOrEmail = async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
if (user)
return res.status(400).json({ message: "El numero de cédula ya existe" });
const email = await User.findOne({ email: req.body.email });
if (email)
return res.status(400).json({ message: "El correo electrónico ya existe" });
next();
} catch (error) {
res.status(500).json({ message: error });
}
};
const checkRolesExisted = (req, res, next) => {
if (req.body.roles) {
for (let i = 0; i < req.body.roles.length; i++) {
if (!ROLES.includes(req.body.roles[i])) {
return res.status(400).json({
message: `Role ${req.body.roles[i]} does not exist`,
});
}
}
}
next();
};
export { checkDuplicateUsernameOrEmail, checkRolesExisted };
//
import * as authJwt from "./authJwt";
import * as verifySignup from "./verifySignup";
export { authJwt, verifySignup };
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
this is a part of my model
router.get('/subscription', function (req, res, next) {
var membership = require('../controllers/membership.js');
var jData = membership.getAll(req, res);
res.render('subscription', { title: 'Subscription', data : jData });
});
this is a part of my controller.js
var db = require('../db.js');
module.exports = {
//home: function (req, res, next) {
// res.send('home page');
//},
insert: function (req, res) {
var body = req.body; //_.pick(req.body, 'description', 'completed');
db.membership.create(body).then(function (membership) {
res.json(membership.toJSON());
}, function (e) {
res.status(500).json(e);
});
},
updateById: function (req, res, next) {
//var Id = parseInt(req.params.id, 10);
var body = req.body;
db.membership.update(body, { where: { id: parseInt(_.propertyOf(body)('id'), 10) } }).then(function (membership) {
if (!!membership) {
res.json(membership.toJSON());
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).json(e);
});
},
deleteById: function (req, res, next) {
//var Id = parseInt(req.params.id, 10);
var body = req.body;
db.membership.destroy({ where: { id: parseInt(_.propertyOf(body)('id'), 10) } }).then(function (membership) {
if (!!membership) {
console.log('The Row with the Id : ' + _.propertyOf(body)('id') + ' deleted successfully!');
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).json(e);
});
},
deleteAll: function (req, res, next) {
db.membership.truncate().then(function () {
console.log('All rows deleted successfully!');
}, function (e) {
res.status(500).json(e);
});
},
getById: function (req, res) {
var Id = parseInt(req.params.id, 10);
db.membership.findById(Id).then(function (membership) {
if (!!membership) {
console.log('\n\nMEMBERSHIP : ' + JSON.stringify(membership.toJSON()));
res.json(membership.toJSON());
//return membership.toJSON();
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).send();
});
},
getAll: function (req, res) {
var where = {};
db.membership.findAll({
where: where
}).then(function (membership) {
res.json(membership.toJSON());
}, function (e) {
res.status(500).send();
});
}
};
i am trying to get aal data in my model data comes perfectly so no issue in controller
but res.render function data could not be passed to jade.
according to me res.render function call before jdata variable filled.
any solution about it tell me.
thanks in advance
You can't send the response two times, if you send the res in the controller you can't send it again in the model, you should use a callback:
Controller:
getAll: function(cb) {
var where = {};
db.membership.findAll({
where: where
}).then(function(membership) {
cb({
data: membership.toJSON()
});
}, function(e) {
cb({
error: e
});
});
}
Model:
router.get('/subscription', function (req, res, next) {
var membership = require('../controllers/membership.js');
var jData = membership.getAll(function (cb) {
if (cb.error) res.status(400).send();
res.render('subscription', { title: 'Subscription', data : cb.data });
});
});