Here is my Model:
var mongoose = require('mongoose');
var partySchema = new mongoose.Schema({
partyCode: Number,
partyName: String,
mobileNo: String
});
var Party = module.exports = mongoose.model('Party', partySchema);
module.exports.getAllParties = function(callback){
Party.find().lean().exec(function(err, parties){
if (err) return callback(err, null);
callback(null, parties);
});
};
Here is the Route:
router.get('/', function(req, res, next){
//retrieve all parties from Party model
//mongoose.model('Party').find({}, function (err, parties) {
Party.getAllParties(err, parties){
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"parties" : parties
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(parties);
}
});
}
};
});
At line no 9 in Route.js (Here in above code line no.4) I get an error:
Party.getAllParties(err, parties){
Syntax error: {unexpected token
Why is it unexpected? Can't I use a function's body here???
You need to pass in a function instead. A block statement like that outside unfortunately won't work.
This is most likely what you need:
Party.getAllParties(function (err, parties) {
// rest of your logic here
});
You can't place a block statement these when you're calling a function.
It looks like you want something like
Party.getAllParties(function() {
// ...
})
Where you pass an anonomous callback function
Related
I am trying to send data from my login page to my home page when the user is redirecting to the home page, so that i can use in information in the home ejs file.
Here is my code:
module.exports = function (app) {
app.post('/login', function (req, res) {
var data = {
"email": req.body.email,
"password": req.body.password
}
functions.callAPI("api link", data, function (error, result) {
if (error) {
var response = {
"status": 400,
"message": error,
"data": null
}
res.render('login', { response: response });
} else {
var response = result;
if (response.status === 400) {
res.render('login', { response: response });
} else {
req.session.token = response.data[0].token;
req.session.id = response.data[0].id
res.redirect('/home', { response: response }); //this is where i what to pass the data.
}
}
});
});
}
If, say, the callback to your app.get('/home') is res.render('home')
Change
res.redirect('/home', { response: response });
to
res.render('home', { response: response });
edit 1 :
Since your comment indicate that your get('/home') route is not simply rendering home, do it in this way:
In this module handling app.post('/login'), instead of incorporating the whole route logic, return the callback only, name it as loginCallback in server.js (or app.js or index.js)
And make another module to return the callback of app.get('/home'), name it as homeCallback, make it accept one more argument, for the response, with a default parameter as empty object.
Now this loginCallback will call the homeCallback, passing the third argument.
This can achieve your purpose.
I am trying to use hapi-auth-bearer-simple module to enable bearer token on my app. However, I am getting the error shown in the title.
I am trying to implement this module to enable token authorisation in my app But I am getting error mentioned below
e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\node_modules\hoek\lib\index.js:723
I have a route file
module.exports = [
{
method: 'GET',
path: '/api/{_id?}',
handler: function (request, reply) {
Controller.control.get(request.params, function (err, success) {
console.log(request.params);
if (err) {
reply(unifunc.sendError(err));
} else {
reply(unifunc.sendSuccess(SuccessMsg,success)).code(200);
}
});
},
config: {
description: 'desc',
tags: ['api', 'oV'],
validate: {
headers: unifunc.authorizationHeaderObj,
params: {
o_id: Joi.string().required().trim(),
_id: Joi.string().optional().trim()
},
failAction: unifunc.failActionFunction
},
auth: {
strategy: 'bearer',
scope: ['admin', 'user-{params.id}']
},
plugins: {
'hapi-swagger': {
responseMessages: msgs
}](url)
and a controller file in which I mentioned strategy
var bearerSimple= require('hapi-auth-bearer-simple')
authorization = Authorization.auth; // This plugin has the logic to validate the token and return the error in case it fails and I am passing accesstoken as parameter in a function in that file
var getV = function(server, params, callbackRoute){
server.register(
[{
register: bearerSimple
}], function(err){
if(err){
console.log("Failed to log the plugin",err);
throw err;
}
server.auth.strategy('bearer', 'bearerAuth', {
authorization : authorization
});
});
console.log(params);
async.series([
function(cb){}
]}
complete error message is:
Error: Unknown authentication strategy: bearer in path: /api/orders/{order_id}/vehicles/{_id?}
at Object.exports.assert (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\node_modules\hoek\lib\index.js:723:11)
at e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\auth.js:152:14
at Array.forEach (native)
at internals.Auth._setupRoute (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\auth.js:149:24)
at new module.exports.internals.Route (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\route.js:142:47)
at internals.Connection._addRoute (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\connection.js:375:17)
at internals.Connection._route (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\connection.js:367:18)
at wrappedRoute [as _route] (e:\python_training\Training\Node\Test\Project\Backend\node_modules\newrelic\lib\instrumentation\hapi.js:222:29)
at internals.Plugin._apply (e:\python_training\Training\Node\Test\Project\Backend\node_modules\hapi\lib\plugin.js:460:14)
at internals.Plugin.route
Is there any way I can resolve this issue?
Edit:
I modified server.js file and removed the strategy from controller file
I placed strategy in server.js
var validationFunction = Authorization.auth;
console.log(validationFunction);
server.register(
[{
register: bearerSimple
}], function(err){
if(err){
console.log("Failed to log the plugin",err);
throw err;
}
server.auth.strategy('bearer', 'bearerAuth', {
validationFunction : validationFunction
});
});
and in Authorization file looks like this
function rauth(accessToken, cb) {
var criteria = {accessToken: accessToken};
var projection = {};
var options = {limit: 1};
Service.AdminService.getadmin(criteria, projection, options, function (err, data) {
if (err) {
cb(err);
} else if (data && data.length > 0 && data[0]._id) {
console.log(data);
console.log(data.length);
adminId = data[0]._id;
cb()
} else {
cb(UniversalFunctions.CONFIG.APP_CONSTANTS.STATUS_MSG.ERROR.INVALID_ACCESS_TOKEN);
}
});
Now I am getting this error:
Error: options.validateFunc must be a valid function in bearerAuthentication scheme
I have been breaking my head over this problem from days. Could anyone suggest what could be the problem here?
The only problem I found was with the parameters of callback function passed in validateFunction but I can't remove the parameters as those parameters are being defined in another function called getadmin. Could anyone suggest a workaround for this?
Solved in this issue https://github.com/Salesflare/hapi-auth-bearer-simple/issues/69.
The problems were a typo and needed to pass more info back on a successful authorization.
I want to call a function in the same controller but I mostly have an error like: "ReferenceError: myFunctionB is not defined"
module.exports = {
myfunctionA: function(req, res){
var theword;
theword = myFunctionB({id:26})
return res.json({say:theword})
},
myfunctionB: function(req, res){
var id = req.param('id');
niceword.get({
id:id
}, function(err, word){
if(err){return res.negotiate(err);}
if(!word){return res.json({err:"no word found"})}
return res.json({word:word});
})
}
}
I also tryed by to put myFunctionB into a service but, as I use many other controller etc I have no response.. Any idea?
There are a few ways to do this. The proper way, as yBrodsky says, is to create a service that runs a callback or returns a promise:
myServiceFunctionB: function(params, cb) {
var id = params.id;
niceword.get({
id:id
}, function(err, word){
return cb({ say: { word: word });
});
}
And then in your controller, just use:
return MyServiceName.myServiceFunctionB({id: 26}, res.json);
You can also pass in your req and res to continue using those:
myServiceFunctionB: function(req, res) { ...
Alternatively, you can use the this keyword in your controller:
myfunctionA: function(req, res){
req.params.id = 26;
return this.myfunctionB(req, res);
}
If you'll be doing more complicated logic where context gets lost, just set a new var at the start using this:
myfunctionA: function(req, res){
var self = this;
req.params.id = 26;
//...lots of nested promises or callbacks...
return self.myfunctionB(req, res);
}
Thank you yBrodsky and wwwslinge, I finaly get what I need thank of you.
I had to make a little change because I still need to use the data after they pass into the function.
Controller
MyServiceName.functionB({id:1}, function(data){
// doing some stuff with the data and then
return res.json({data: data});
});
Service
functionB: function(params, cb){
var id = params.id;
Niceword.getbyid({
id:id
}, function(err, word){
if(err){return err}
return cb({word:word});
})
}
I've set up a node.js server-app that I want to do some parse.com requests.
I basically want it to return the parse-object JSON-representation.
My route:
var blog = require('./models/model');
app.get('/api/article/:permalink', function(req, res) {
res.json(blog.getArticle(req.params.permalink));
});
And my model:
var Parse = require('parse/node').Parse, // load the parse for node package
keys = require('../../config/keys'); // keys config-file for hosted services
Parse.initialize(keys.app, keys.js);
module.exports = {
getArticle: function(permalink) {
"use strict";
var Article = Parse.Object.extend('Article');
var query = new Parse.Query(Article);
query.include('category');
query.include('profile');
query.equalTo('permalink', permalink);
query.find().then(function(results) {
return results;
}, function(error) {
return error;
});
}
};
The thing is, this returns nothing when I call an article with a permalink that I know to exist (example: http://localhost/api/article/testFoo). I don't get any errors either.
My browser console flashes a message for a split second that reads:
Resource interpreted as Document but transferred with MIME type application/json: "http://localhost/api/article/testFoo"
Any suggestions to what I am doing wrong?
You are trying to use the return value of an async function. This can't work, you need to pass a callback (or the res object) to your getArticle function, which will then use it to send the data back.
With a callback:
app.get('/api/article/:permalink', function(req, res) {
blog.getArticle(req.params.permalink, function(data) {res.json(data)});
});
...
getArticle: function(permalink,callback) {
...
query.find().then(function(results) {
callback(results);
}, function(error) {
callback({error: error});
});
{ text: undefined,
done: false,
_id: 529e16025f5222dc36000002,
__v: 0 }
PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b
I keep getting this error when trying to do an update for my simple CRUD todo list. When I submit the update, the change doesn't appear on screen, although the put says it's a 200. Not sure what steps to take so that I don't get this "undefined" error and so I can have the update show up on screen.
EDIT: Included more code
This is the back-end node code:
app.put('/api/todos/:_id', function(req, res) {
Todo.findById(req.params._id, function(err, todos){
todos.text = req.body.text;
console.log(todos);
todos.save(function() {
if (!err) {
res.send(todos);
} else if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
});
});
});
This is the Angular front-end code:
$scope.updateTodo = function(id) {
$scope.newItem = prompt("Please enter your new item:", "");
$http.put('/api/todos/' + id, {formData: $scope.newItem}).success(function(data) {
$scope.todos = data;
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
});
};
I think it's because of this:
$http.put('/api/todos/' + id, { formData: $scope.newItem} )
^^^^^^^^
You're passing a single formData parameter with the request, yet in your Express code, you use this:
req.body.text
Either try this:
req.body.formData.text
Or don't use the formData parameter at all and pass $scope.newItem directly.
Besides that, your Express code is a bit messy: it might send back multiple responses and it doesn't check for errors on the save (as #PaulGray also pointed out).