Node.js & Sequelize : res.json on findAll? - node.js

I have an issue with Res.json in the code below :
/* GET all users */
app.get('/users', function (res) {
db.users.findAll()
.then(users => {
res.json(users);
});
});
It worked pretty well yersteday but now, it doesn't. I have this error for all res.json only with the app.get which uses findAll...
Unhandled rejection TypeError: res.json is not a function
I don't understand why res.json is working in all my fonctions but not with findAll :/

The callback prototype / signature is wrong, it should be like that :
app.get('/users', function(req, res) { ... })
In your example, you're trying to call req.json, which doesn't exists.
Hope it helps,
Best regards
EDIT
If you don't want the req, you can't just remove it, because Express expect it to be there, so he will call your anonymous functio with the 3 usual parameters : req, res, and next.
Express cannot guess that you want res as first parameter of your function.
But if you want other people to know that you will not use this variable, you could do something like that :
app.get('/users', function(_, res) { ... })
OR
app.get('/users', function(_req, res) { ... })
It is an acceptable practice to prefix useless variables with an underscore, if the underscore has no other meaning. Don't do that if you use underscore.js or lodash

Related

I cant use a function returning another function in a express js helper

I have this helper :
function loginRequired(msg){ // this is the helper
return function(req, res, next){
if (req.user.is_authenticated){ // example
return next()
}
//else
req.flash('error_msg',msg)
return res.redirect('/')
}
}
and I have this route ( I`m using the helper in this route ) :
router.post('/new', loginRequired(msg='You are not allowed here'), async (req, res)=>{
// code
})
The problem is that the function returned by the helper is not being executed, when I request this route, it keeps loading forever and the content is never sent.
There isn't anything obviously wrong with the loginRequired() function and how you're using it so the problem is probably elsewhere. The only thing I see is that if req.user doesn't exist, then it would throw.
For further debugging, I would suggest you do this to make sure your route is being matched.
function logRoute(msg) {
return function(req, res, next) {
console.log(msg);
next();
}
}
router.post('/new', logRoute("/new handler"), loginRequired(msg='You are not allowed here'), async (req, res)=>{
// code
});
And, make sure you see /new handler in the console. If you don't even see that, then the problem is further upstream with how your route is declared as it isn't matching an incoming request. You would have to show us the rest of that code for us to see how the router is being used.

Node JS Express same thing for route GET and POST

I am working with nodejs/express. I want to do the same thing for a route, for GET and POST http requests.
I am doing this:
app.get('/', function(req, res) {
// Some code
});
app.post('/', function(req, res) {
// Same code
});
Is there a way to refactor get and post in the same callback ?
Thanks
Or you can use all, if your site doesn't use any other methods in particular:
app.all('/', handler)
This seems like a very odd requirement. If the behavior is exactly the same just specify one function to handle both:
function myHandler(req, res) {
// Some code
}
app.get('/', myHandler);
app.post('/', myHandler);
A bit old question but still facing today.
If you want to expose the api for all method with the same handler:
function sameHandler(req, res) {
// do something here
}
app.all('/', sameHandler);
If just wanna use the same route but with different handlers:
function getHandler(req, res) {
// do something here
}
function postHandler(req, res) {
// do something here
}
function deleteHandler(req, res) {
// do something here
}
app.route('/').get(getHandler).post(postHandler).delete(deleteHandler);

Express router - :id?

Real simple question guys: I see a lot of books/code snippets use the following syntax in the router:
app.use('/todos/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
I'm not sure how to interpret the route here... will it route '/todos/anything'? and then grab the 'anything' and treat is at variable ID? how do I use that variable? I'm sure this is a quick answer, I just haven't seen this syntax before.
This is an express middleware.
In this case, yes, it will route /todos/anything, and then req.params.id will be set to 'anything'
On your code, that is for express framework middleware, if you want to get any id in the server code using that route, you will get that id by req.params.id.
app.use('/todos/:id', function (req, res, next) {
console.log('Request Id:', req.params.id);
next();
});
Route path: /student/:studentID/books/:bookId
Request URL: http://localhost:xxxx/student/34/books/2424
req.params: { "studentID": "34", "bookId": "2424" }
app.get('/student/:studentID/books/:bookId', function (req, res) {
res.send(req.params);
});
Similarly for your code:
Route path: /todos/:id
Request URL: http://localhost:xxxx/todos/36
req.params: { "id": "36" }
app.use('/todos/:id', function (req, res, next) {
console.log('Request Id:', req.params.id);
next();
});
Yes, in your example youl get req.params.id set to 'anything'
A bit late to the party but the question mark in your question made me think of something that hasn't been touched upon.
If your route had a question mark after the id like so: '/todos/:id?', id would be an optional parameter, meaning you could do a getAll() if id was omitted (and therefore undefined).
This is called Path params and it's used to identify a specific resource.
and as all answer how to get the value of the path params
app.use('/todos/:id', function (req, res) {
console.log('Request Id:', req.params.id); // 'anything'
});
read more about params type
https://swagger.io/docs/specification/describing-parameters/

using middlewares for specific namespaces in restify

I would like to use a middleware for checking users credentials only for some routes (those that start with /user/), but to my surprise server.use does not take a route as first argument and with restify-namespace server.use effect is still global.
Is there other way better than passing my auth middleware to all routes alongside the controller?
I think I'm going to just use server.use and inside the middleware make the following route check:
if (req.url.indexOf('/user/') !== 0) {
return next();
}
Unfortunately restify doesn't seem to be like express, which support the * operator. Hence, What I would suggest is grouping the routes that you desire together and apply a .use before them.
That is:
server.get('/test', function(req, res, next) {
// no magic here. server.use hasn't been called yet.
});
server.use(function(req, res, next) {
// do your magic here
if(some condition) {
// magic worked!
next(); // call to move on to the next middleware.
} else {
// crap magic failed return error perhaps?
next(new Error('some error')); // to let the error handler handle it.
}
});
server.get('/admin/', function(req, res, next) {
// magic has to be performed prior to getting here!
});
server.get('/admin/users', function(req, res, next) {
// magic has to be performed prior to getting here!
});
However, I would personally advocate the use of express, but choose whatever fits your need.

what is "next()" in nodejs (expressjs)? [duplicate]

I see a lot of use next in node.js.
What is it, where does it come from? What does it do? Can I use it client side?
Sorry it's used for example here:
http://dailyjs.com/2010/12/06/node-tutorial-5/
look for the loadUser function.
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets/
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).
There's nothing special about the name next in this example; we could have named it anything.
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
http://howtonode.org/control-flow-part-ii
It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...
So you can do something like this as a simple next() example:
app.get("/", (req, res, next) => {
console.log("req:", req, "res:", res);
res.send(["data": "whatever"]);
next();
},(req, res) =>
console.log("it's all done!");
);
It's also very useful when you'd like to have a middleware in your app...
To load the middleware function, call app.use(), specifying the
middleware function. For example, the following code loads the
myLogger middleware function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next();
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
})
app.listen(3000);

Resources