Sails data from service to controller - javascript

I'm starting with sails js and node more generally .
I'm trying to use the regular way of implementing services in sails to pass data in my controller.
for example, I've a dashboard view, called dashboard.ejs
my view is correctly routed and everything.
But the regular ways of passing data from service wasn't working at all, and I ended up with that to make it work, which seems to be very unappropriate:
my CountService.js:
module.exports = {
RoomCount: function(req, res, cb, tab)
{
Room.count().exec(function(err, roomfound){
tab.push(roomfound);
cb(req, res, tab);
});
},
VenteCount: function(req, res, cb, tab)
{
Vente.count().exec(function(err, ventefound){
tab.push(ventefound);
cb(req, res, tab);
});
},
LotCount: function(req, res, cb, tab)
{
Lot.count().exec(function(err, lotfound){
tab.push(lotfound);
cb(req, res, tab);
});
}
};
My DashboardController.js
module.exports = {
dashboard: function(req, res, next)
{
var tab = []
var end_dashboard = function(req, res, tab){
res.view('dashboard', {
roomCount: tab[0],
venteCount: tab[1],
lotCount: tab[2]
});
};
var callbacklot = function(req, res, tab){
end_dashboard(req, res, tab);
};
var callbackvente = function(req, res, tab){
CountService.LotCount(req, res, callbacklot, tab);
};
var callbackroom = function(req, res, tab){
CountService.VenteCount(req, res, callbackvente, tab);
};
CountService.RoomCount(req, res, callbackroom, tab);
},
};
And then I can call the VenteCount etc values in my view ejs
The regular way was giving a value = undefined
I think I was wrong in the res() or next() part so I ended like that but it makes the service thing very complicated...
Thanks a lot for your help

Related

express next throwing error as next is not defined

I am trying to pass some predefined functions in the callback of app.post() method. I am getting next is not defined error. Below is my code. Please suggest where I am doing wrong or am I missing any concept here?
var express = require('express');
var app = express()
app.post('/api/signup', function(req, res) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
where I have each function defined and imported and returning next() after my process.
my validateParams function is below :
validateParams = function(req, res, next) {
console.log("at validator ", req);
next();
}
module.exports = validateParams;
my dbCall function is below :
dbCall = function(req, res, next) {
console.log("at dbCall ", req);
next();
}
module.exports = dbCall;
my sendResponse function is below :
sendResponse = function(req, res) {
console.log("at dbCall ", res);
res.send("Response sent successfully");
}
module.exports = sendResponse;
You probably forgot to add the next argument in your callback.
app.post('/api/signup', function(req, res, next) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
I think you are trying to use validateParams(req, res, next) and dbCall(req, res, next) as middleware functions. In this case, you need something like this:
const validateParams = (req, res, next) => {
// do stuff here
next();
}
const dbCall = (req, res, next) => {
// do stuff here
next();
}
app.post('/api/signup', validateParams, dbCall, function(req, res) {
sendResponse(req, res)
})
You can read more here

NodeJs routing middleware error

I am trying to implement a middleware that will check if a user is authenticated before the server delivers a page. Although it looks like the process of doing this is simple, node is throwing an error which says "Can't set headers after they are sent".
My router's code is:
module.exports = function(app) {
app.get('/', checkAuth, require('./myAuthenticatedPage').get);
app.get('/login', require('./myLoginPage').get);
};
The myAuthenticatedPage.js:
exports.get = function(req, res) {
res.render('index');
};
The myLoginPage.js:
exports.get = function(req, res) {
res.render('login');
};
The checkAuth.js:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
}
next();
}
Any help on this will be greatly appreciated.
Thanks
If you aren't authenticated, you'll redirect the user and then try to render the index page. This causes the http headers to be sent twice, hence the error "Can't set headers after they are sent".
In checkAuth.js try:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
} else {
next();
}
}

Express 4 router.route: route not found

I'm running into a strange issue. The first route is working, but the parameterized route returns a 404 error.
var express = require('express');
var router = express.Router();
router.route('/')
.get(function (req, res, next) {
res.send('A list of vehicles.');
})
.post(function (req, res, next) {
res.send('You added a vehicle!');
});
router.route('/:id')
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
.put(function (req, res, next, id) {
res.send('You edited vehicle: ' + id);
});
If I add this route:
router.route('/test')
.get(function (req, res, next) {
res.send('This is a test.');
});
...I can hit that endpoint. This also seems to work with another router I'm using, which is using router.get(path, function) and router.post(path, function) instead of the router.route(path).get()... methodology.
Am I missing something obvious here? I'm using Express ~4.12.
Gah, I'm an idiot. Just figured this out. I saw an example that used this function signature:
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
This apparently doesn't work. I'm not sure if the http methods check the arity of the function, but this did work:
.get(function (req, res, next) {
res.send('Vehicle: ' + req.params.id);
})
I don't remember where I saw that example, but hopefully this helps someone.

HTTP requests in Express NodeJS

I have the following code from https://github.com/chjj/tty.js/:
this.get("/hola", function(res) {
iniciar();
});
function iniciar() {
self.init();
}
iniciar();
going to localhost:8080/hola, it does not load. localhost:8080 works perfectly. self.init() calls a function that, in turn, calls other functions. The problem seems to be the following called function:
Server.prototype.initMiddleware = function() {
var self = this
, conf = this.conf;
this.use(function(req, res, next) {
var setHeader = res.setHeader;
res.setHeader = function(name) {
switch (name) {
case 'Cache-Control':
case 'Last-Modified':
case 'ETag':
return;
}
return setHeader.apply(res, arguments);
};
next();
});
this.use(function(req, res, next) {
return self._auth(req, res, next);
});
this.use(term.middleware());
this.use(this.app.router);
this.use(express.static(__dirname + '/../static'));
};
According to express.js documentation:
// a middleware sub-stack which prints request info for any type of HTTP request to /user/:id
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
So, it seems that there are "conflicts" between first app.get and the others app.use or this.use. How can I solve that?
it's because you are not returnig anything and then the browser is polling this until it return something.
this.app.get("/hola", function(req, res) {
res.writeHead(200, {'content-type':'text/html'});
res.end('/*html code here*/');
});

Expressjs routes with username

Im trying to use the username as route in expressjs, to view their profile.
app.get('/:username', function (req, res, next) {
users.get_user(req.params.username, function (err, results) {
if(results[0]) {
res.render('/profile', {
title: 'Profile',
userinfo: results[0]
});
} else {
next();
}
});
});
users.get_user is a function wich gets the user from the db. If it doesn't find a user it goes on to the next route. I also have a lot of other pages like /start, /forum etc. Is this an insufficient way of doing this, because theres a call to the db each time it passes through the /:username route. My question is, is there a better more sufficient way?
Try defining the more specific routes (e.g. /start, /forum) before the /:username route in your application. Express matches routes in the order that you define them.
E.g. Do this:
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
app.get('/:username', function(req, res, next) {...});
Not
app.get('/:username', function(req, res, next) {...});
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
This way, if the user goes to /start, it won't hit the /:username route and cause a database hit.

Categories

Resources