Request and response seem wrong when using grunt express and ws - node.js

I am using express and ws.
I am able to get it up and running, but when I use app.use(fn) it doesn't seem to use the request and response objects from express, so I am getting errors when I call req.get (to get a request header) and similarly res.status.
To debug I tried running it without grunt-express, but the request and response are correct. Has anyone faced this problem or knows how to fix it?
snippet of code that relates to using grunt-express:
exports = module.exports = app;
app.listen = function() {
return server.listen.apply(server, arguments);
};
I realize that the above snippet is not exactly what is told in the README of grunt-express, but:
server.use = function () {
return app.use.apply(app, arguments);
}
Did not work for me, because grunt-express relied on so much more.
I am also open to use any library you have tried out that lets me run an express server while allowing me to hot load the front-end on development.

Related

nodejs Express: how come there no docmentation on res.respond but res.respond works?

I have adopted a nodejs Express project where there are res.respond(...) for every route. e.g.:
res.respond({
message: "OK"
})
The routes works just fine.
However when I started to add new routes and implement code myself, I suddenly realized that there is no such API called res.respond() in Express whatsoever.
I need to use res.status(200).send() or res.status(200).json() to respond back to client and finish the req-res cycle.
How is this possible?

Validate my understanding on Express Routes

Actually, before I get into the question, when I do anything like
const app = express()
app is an instance of the entire express module right? Meaning, when I do app.route, route is it an Express method right or a NodeJS method, since Node has .route as well? Anyways... I just wanted to double check this.
app.route('/games')
.post(postGame)
.get(getGames);
app.route('/games/:id');
.get(getGame)
.delete(deleteGame);
Is this the same as... and if not... why would one choose one over the other?
app.get('/games');
app.post('/games');
app.get('/games/:id');
app.delete('games/:id');
Sorry, it's just been a while since I have used Express, and couldn't find anything about this specific problem. Thanks!
app is an instance of the entire express module right?
Yes, the app object is create by calling the top-level express() function exported by the Express module. That set the default http headers, render options.... and wrap the http node module:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
You can see more in the source code here (really readble)
route is it an Express method right or a NodeJS method
Route is an express object and nodeJs don't provide a routing system like express.
And for your example yes it's totally the same. They stores the handlers function in the same this._router.route

Nodejs Express sendStatus error

The web app uses express for the server, nodejs as the language, mongodb as the database and mongoose as the wrapper. Express is running a server at port 3000 and I'm trying to implement a basic CRUD for a collection.
I've used restify before and normally doing a res.send(406, "err - body"); doesn't cause any issues however I can't seem to figure it out with express.
Looking at express' documentation, res.status(404).send('Bad Request'); is how you send a status code with a custom message back. It works when there's some sort of invalid input but when I try to save to mongodb
newSchema.save(function(err){
if (err) {
res.status(500).send('error saving');
} else {
res.sendStatus(200);
}
});
and call res.sendStats(200); it gives me the error: Error: Can't set headers after they are sent. When using a httprequester, the error is 404 and Cannot POST /user/create.
Are you sending another response afterwards? Ie... maybe you're doing something like:
if (!err){
res.send()
}
wherever the function is called (or after the code you pasted). And obviously, this could be the source of your error, since you'd be sending two separate responses.
Apparently, it's not a good idea to copy restify code into express. I had a next(); which doesn't work with express or it does but as of right now, I don't need to use it.
Instead of res.sendStatus(), I changed to res.send(), and it works beautifully.

mean.js $resource to call express server RESTful API

I come from a completely non web-development background, but having seen the traction that mean.js is picking up, i really wanted to give it a shot.
I've followed tutorials online so I've basically started, run and modified the example app but am now trying to do something thats off of the tutorials. As a result I have a basic understanding of express and angular
I've been trying to integrate the activator npm package (https://www.npmjs.org/package/activator) into the app, and while I've managed to fit in the angular bits, I'm having trouble plugging in the express bits. Which brings me to a very fundamental doubt, the answers to which I haven't really been able to find. I know that in Mean, the angular code connects to the express code using REST API's created in express. And that I believe happens using angular services. But I don't understand how. For instance, the users module has the following service defined:
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users', {}, {
update: {
method: 'PUT'
}
});
}
]);
Can anyone explain how this works ?
Also if I have some code on the express side say:
var sayHello = function(name){
return "Hello"+name;
}
How can I call this through angular? I know we use $resource for that from the ngResource module, but I dont really understand how.
Any help would be much appreciated.
Connecting these things together can be a bit confusing. I think the thing to understand is that when using Express on the server side, you need to model your API around a route, and handle communication with the req and res objects you'll be handed.
So first on the client side, taking a simple example, I generally use the $resource as a way of wrapping the HTTP/ajax details which I don't want to worry about. So I'll write my service as such:
"use strict";
angular.module("myModule").factory("UserService", ["$resource",
function($resource) {
var resource;
resource = $resource("/api/users", null, {
listUsers: {
method: "GET",
isArray: true
}
});
return resource;
}
]);
(Notice that I'm passing the isArray parameter to this resource since I expect an array of users to return -- which is not always the case with all APIs).
Then to take advantage of that resource, perhaps in my controller I'll have code like this:
"use strict";
angular.module("myModule").controller("UserCtrl", ["$scope", "UserService",
function($scope, userService) {
$scope.loadUsers = function() {
userService.listUsers(function(resource, headers) {
// this function is called on success, with the result
// stored within the `resource` variable
// ...
}, function(response) {
// this function is called on error
// ...
});
};
}
]);
Now assuming everything goes right on the server side, we'll receive our list of users to play around with passed in to the first function as the resource.
On the server side, we'll need to configure our routes (wherever those are configured) to include our users controller, which will serve as our users API. So perhaps within this app we have a routes directory which contains all our Express routes (see the app.route documentation for more information on Express routes). We also have a controllers directory which contains all our Express controllers that handle the logic for our routes. Keeping with the "users" example, we'll have a route defined that matches the /api/users $resource route we defined above in our Angular code:
"use strict";
var controller = require("../controllers/user");
module.exports = function(app) {
app.route("/api/users").get(controller.listUsers);
};
This code takes in the Express app as input, and defines a single route for /api/users as a GET HTTP request (notice the .get function called). The logic for this route is defined in the user controller, which would be something like this:
"use strict";
exports.listUsers = function(req, res) {
var users;
// ...somehow populate the users to return...
res.send(users);
};
We've left the details on how to populate that array of users, but hopefully this gives you the idea. This controller is passed the req (request) and res (response) HTTP objects as input, so it can query the request object for details on what the user passed in, and must send some response back to the user to complete the request/response loop. In this example I'm using the res.send function to simply send back our JavaScript array (which will be passed as JSON).
Does that make sense?

accessing required modules from other modules

I have a bare-bone express application, exactly the one that is created with the express command.
I have installed socket.io and attached it to my server, like this:
var app = express(),
server = http.createServer(app),
io = io.listen(server);
server.listen(8000);
Now, I also have the routes files, which is called like this:
app.get('/', routes.index);
Inside this module I have the following function:
exports.index = function(req, res){
socket.emit('news', { message: "foo" });
};
This obviously leads to a 500 reference error, because the routes file is an exportable module, and obviously has no idea what the socket is, as it is located in the app.js file.
Is there a way I can access this socket object from this, or any other file? Please note that it is attached to the express generated app. Here is a link to said project: http://jsfiddle.net/E27yN
extra: what about getting/setting session data?
Thanks in advance.
If I'm reading this correctly, I had a very similar problem: Handling Node.js Async Returns with "require" (Node ORM)
The way I resolved it was by putting a function call to the require, and returning that function in my exports, then that was accessible via that local variable. In your case, I think it'd be something like this:
var routes = require("routes.js")(io);
console.log(routes.index()); // will log return of the function "index" in routes.js.
// in routes.js
module.exports = function(io) {
var exports = this;
exports.index = function(req,res,io) {
// now io.socket is available to routes
console.log(io);
}
return exports;
}
Now you can access whatever you've exported by using that variable. So getting and setting session data would be a matter of getting that info to/from the proper place and modifying it in your parent file (usually whatever you're launching with node, like app.js or what have you).
Hope this helps!
EDIT: After discussing this in the comments, I think the problem is you're trying to use express and socket.io on the same port.
The example they give in your link (http://socket.io/#how-to-use) actually shows that they are serving up index.html from app.get("/"). Index.html includes the socket.io script file () which is by default served up when you start your socket server.
That would look like this jsfiddle: http://jsfiddle.net/Lytpx/
Note that you serve up the index.html page through express, but your socket service actually serves up /socket.io.js which then makes connection calls to the listening socket service (note, you may want to change localhost in your io.connect call in index.html to whatever your server is).

Resources