Express.js request params undefined - javascript

I've got the following node/express code:
app.get("/notes/:categoryName", function (res, req) {
var categoryName = req.params.categoryName;
res.render("notes", {title: categoryName});
});
But when I look at req.params, it's undefined.
Yet, in another controller it works fine:
app.get("/api/notes/:categoryName", function (req, res) {
var categoryName = req.params.categoryName;
data.getNotes(categoryName, function (err, notes) {
if (err) {
res.send(400, err);
} else {
res.set("Content-Type", "application/json");
res.send(notes.notes);
}
});
});
What's the deal?

app.get("/notes/:categoryName", function (res, req) {
More attention :
app.get("/notes/:categoryName", function (req, res) {
You switched the params (res, req)

Related

My second endpoint doesn't work for node-js API, why?

Trying to make my first API. It was going well, except for some reason my second route, app.route('characters/:characterId') isn't working. None of the endpoints work, even though the first route, app.route('/characters') works fine. I've been on this for like an hour and I have no idea what's going on.
Help?
Here is the controller
'use strict';
var mongoose = require('mongoose'),
Character = mongoose.model('Characters')
exports.list_all_characters = function(req, res) {
Character.find({}, function(error, character){
if (error)
res.send(error);
res.json(character)
})
}
exports.create_a_character = function(req, res) {
var new_character = new Character(req.body);
new_character.save(function(error, character){
if (error)
res.send(err);
res.json(character);
});
};
exports.get_a_character = function(req, res) {
Character.findbyId(req.params.characterId, function(error, character){
if(error)
res.send(err);
res.json(character);
});
}
exports.update_a_character = function(req, res) {
Character.findByIdAndUpdate({_id: req.params.characterId}, req.body, {new: true}, function(error){
if (error)
res.send(error);
res.json(character);
});
};
exports.delete_a_character = function(req, res) {
Character.remove({_id: req.params.characterId}, function(error, character) {
if(error) {
res.send(error);
res.json({message: 'Character Deleted'});
}
})
}
Here is the router
'use strict';
module.exports = function(app) {
var characterList = require('../controllers/characterListController')
app.route('/characters')
.get(characterList.list_all_characters)
.post(characterList.create_a_character);
app.route('characters/:characterId')
.get(characterList.get_a_character)
.put(characterList.update_a_character)
.delete(characterList.delete_a_character);
};
You are missing a /
app.route('/characters/:characterId')

How do I use a callback to fetch data from mysql with node.js and ejs?

I need to fetch foo from the query below:
exports.get = function(id, cb) {
sql = 'SELECT `sidebar`, `test` FROM users WHERE `id` = "' + id + '"';
con.query(sql, function(err, foo) {
if (err) { return cb(err) }
else { return cb(foo) };
});
}
Then render foo on my app.js like this:
app.get('/dashboard', ensureLoggedIn('/login'),
function(req, res) {
const id = req.session.passport.user;
const foo = db.defaults.set(id) //db.defaults.set calls the query
console.log(foo); //prints undefined
res.render('dashboard', { foo:foo });
});
This was my latest attempt:
app.get('/dashboard', ensureLoggedIn('/login'),
function(req, res, next) {
const id = req.session.passport.user;
db.defaults.get(id, function(err, foo) {
if (err) return next(err);
res.render('dashboard', {foo:foo});
//also tried:
//return res.render('dashboard', {foo:foo});
});
The attempt above doesn't render the page at all. The html loads as:
[object object]
What am I missing?
You're trying to render server side a template asynchronously (after fetching the data) and you can't do that.
What you can do is send synchronously the template to the client and then expose an endpoint to fetch those data and modify the page accordingly (on the client).
app.get('/dashboard', ensureLoggedIn('/login'), function(req, res) {
res.render('dashboard');
});
app.get('/fetchdata', function (req, res, next) {
const id = req.session.passport.user;
db.defaults.get(id, function(err, foo) {
if (err) return next(err);
res.send(foo);
});
})

Pass arguments to nested function

I have some code duplication that I'd like to factorize.
app.post('/login', (req, res) =>{
reqOptions = {...};
request(reqOptions, (error, response, body) => {
if (!error) {
res.statusCode = response.statusCode;
res.json(body)
}
else {
res.statusCode = 503;
res.json(body)
}
});
});
The logic in the request callback is always the same, and I try to find a way to get it out into a reusable function, like this :
function requestCallback(error, reponse, body) {
....
}
app.post('/login', (req, res) =>{
reqOptions = {...};
request(reqOptions, requestCallback);
});
My problem is : how can I get access to req and res in the requestCallback() function ? Do I need to pass everything as arguments ?
Many thx
You can use Function.prototype.bind()
function requestCallback(_req, _res, error, reponse, body) {
....
}
request(reqOptions, requestCallback.bind(null, req, res));
Yes, you can just simply pass req and res as arguments to requestCallback()

Node.js, wordpress,redis

I need to get data from Redis in node server and send it to a Wordpress layout. I tried the following, but data doesn't seem to get sent.
var express = require('express');
var app = express();
var redis = require('redis');
var client = redis.createClient(); //creates a new client
client.on('connect', function () {
console.log('connected');
});
data = [];
client.set(['first', 'Oleh']);
client.set(['second', 'Ivan']);
client.set(['thirt', 'Andriy']);
client.set(['fourth', 'Olena']);
client.set(['fifth', 'Kristy']);
client.set(['sixth', 'Irina']);
client.get('first', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('second', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('thirt', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('fourth', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('fifth', function (err, reply) {
console.log(reply);
data.push(reply);
});
client.get('sixth', function (err, reply) {
console.log(reply);
data.push(reply)
});
app.get('http://localhost/wordpress/', function (req, res) {
res.type('application/json'); // set content-type
res.send(this.data); // send text response
console.log(this.data);
});
app.listen(process.env.PORT || 4730);
It seems you have the scope incorrect. this.data refers to the function (req, res) {} and not your global scope.
Try doing res.json(data) and remove the res.type(), as res.json already takes care of that for you.

Remove a field of my json in a specific case

I have an ExpressJS controller that list all my users
userCtrl.get :
get(req, res, next) {
var func = function(err, data) {
if (err) return next(err);
return res.json(data);
};
if (req.params[this.idName])
this._getById(req.params[this.idName], func);
else
this._getAll(func);
}
_getById(id, fn) {
this.ObjectClass.findById(id, fn);
}
_getAll(fn) {
this.ObjectClass.findAll(fn);
}
I'd like to call it from another road, in such a way that res.json() will filter a field of this json
Something like :
router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
function anonJs(x) {
x.forEach(s => s.credential = null);
res.json(x);
}
res.json = anonJs;
userCtrl.get(req, res, next);
});
The problem is, with this last piece of code I end up with a recursion as I call res.json that is now defined as anonJS
You must store the reference to the old function before replacing it.
router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
var json = res.json;
res.json = function(x) {
x.forEach(s => s.credential = null);
json(x);
}
userCtrl.get(req, res, next);
});

Categories