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.
Related
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?
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.
Is it possible to pass in methods instead of just objects in an Express route?
For example, after redirecting to a specific route, I want to execute an alert function.
app.get(res.redirect('/', function(req, res){
alert('this is an alert');
});
);
console.log - seems to be ok, but other methods are not.
I have tried:
res.redirect('/');
alert('this is an alert');
same thing error: ReferenceError: alert is not defined
As, answered below that Alert is a Client side function and not a server side function:
Is there a way that I can tell the server side to pass some client side function after redirecting?
The reason this doesn't work is because node.js and express are on the server side. The alert function has to be executed from the browser as it is a property of browser window objects.
See Node.js Alert Causes Crash
I'm using Context.io's Node.js client library to get the body of emails from my account which is done in my code below.
Once I have that data, I am confused as to how I would get them over to the front-end. I'm new to the whole MEAN stack, and from my research of the basics, I have gathered that with Node, you can make the http calls, parse the json response and then write it to the server, but it seems as if I would have to make an API to then be able to call it from Angular and display it how I wish. I know that with other back-end languages like PHP, you can just write the code within the html, and not need a middle structure to get the info from PHP to the front-end. Is there an easier way than writing my own API in Node after having already made an API request to Context.io?
ctxioClient.accounts(ID).messages().get({limit:10}, function ( err, response) {
if(err) throw err;
console.log("getting responses...");
var messages = response.body;
console.log("message id is " );
console.log(messages.body);
You should implement the backend in JSON using something like res.json and make AJAX requests via Angular $http or something similar.
So when a login fails to validate, I currently respong with res.send(401). However I want to send a snippet of text or html along with the error code.
I tried this:
res.write('string');
res.send(401);
but threw an error and my server wouldn't start.
You're mixing Express methods with the native HTTP methods. Since Express' internally uses the native HTTP modules, you should use one or the other.
// Express
res.status(401);
res.send('string');
// or the shortcut method
res.send(401, 'string');
// HTTP
res.writeHead(401);
res.end('string');
From the examples in express docs
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
A bit more verbose example, but works even when you try to render a template:
res.status(401).send('Unauthorized')
or
res.status(401).render('/401.html')
res.send(error_code,msg);
is deprecated. You should do this instead.
res.status(error_code).send(msg);
Update:
For express v 4.13.4, it will throw error when you do this.
res.status(error_code).send(msg);
saying you can't set headers after they are sent.