Catch and trace middleware exceptions (less-middleware) in Express 3.0 - node.js

First of all, I tried to follow this question (but adapted to Express 3.0):
Nodejs: How to catch an exception from middleware?
app.use(function(err, req, res, next) {
console.error('Middleware exception:' + err.stack);
next(err);
});
However, no matter where I put it in my middleware chain, before or after app.use(lessMiddleware); (from require('less-middleware')) I still get:
GET /? 304 44ms
source : <my path>/style.less
dest : <my path>/style.css
read : <my path>/style.less
DEBUG:
DEBUG: <my path>/node_modules/less-middleware/node_modules/less/lib/less/parser.js:385
throw new(LessError)(e, env);
^
DEBUG: [object Object]
DEBUG: Program node app.js exited with code 1
Kind readers, how to solve this problem? I want to:
Show errror stacktrace
Show server error page instead of crashing

To my surprise the problem was in less-middleware. I kind of expected it to be a more mature solution. I fixed it and made a pull request on Github. Hope this helps anybody encountering the same problem. Cheers.

Related

Node js routes working only locally

I need your help concerning routes in node.js. All newly created routes work fine locally, but not on the remote server after pushing changes. Other urls are still working.
Below is the middleware to capture 404 errors:
// All new routes fall here
app.all('*', function (req, res) {
res.status(404).json({
error: 'Not Found'
});
});
I can confirm that I verified all the config files and I don't know why this is happening.
Could someone explain this to me? Maybe I missed something between local and remote?
I found some similar answers here, here and in the oficial Express page here
Basically, the best way to redirect a 404 error is doing something like this:
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
Read more about it in the links at the top.
Hope it help you.
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
})
You can use the above code to capture 404 errors.
It's possible if you made changes in server and didn't restart nodejs. If you use PM2 try pm2 restart app_name
You can use pm2 start app.js --watch to let pm2 actively watches for any changes in file and restart for you.
For more info about pm2 - http://pm2.keymetrics.io/docs/usage/quick-start/#usage
use following code. it will work .
app.route('/*').get(function(req, res) {
res.status(404).send("page not found!")
});

React giving me 403 forbidden error when making an API call

I am using react to switch images using the Snoowrap Reddit api wrapper. When I use this function just using Node.js and the app module it works normally:
reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
return(post.url.toString());
});
This is what the function looks like with my normal NodeJS app this code here works 100% fine
app.get('/getimage', function(req, res){
r.getSubreddit(subreddit).getRandomSubmission().then(function(post){
if(post.url.includes(".jpg") || post.url.includes(".png")){
res.send(post.url);
res.end();
}
else{
res.send("No picture extension as .jpg .png")
console.log("No .jpg Extension");
}
});
console.log("Pressed!");
});
This code here gives me an unhandled 403 rejection Error I downloaded the chrome browser CORS header extension and it fixed theAccess-Control-Allow-Origin error but now its giving me a 403 error
getPic: function() {
reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
return(post.url.toString());
});
},
A common request that may result in a 403 Forbidden response is a HTTP GET request for a web page performed by a web browser to retrieve the page for display to a user in a browser window.
This maybe caused for the CORS extension, if I was you I would try to configure my server as a CORS server instead of using a chrome extension.
You can use this npm
npm install cors --save
Before your app.get(...) write a const cors = require('cors') and app.use(cors())
I maybe wrong, but give it a try!

Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script

I am creating a progressive web application (pwa) and try to register service worker to test offline feature. The folder structure is like below:
-- views
-- index.pug
-- sw.js
-- public
-- js
-- main.js
-- index.js
index.js file is server file, main.js is the file that being link in each .pug file. I embedded the service worker register code in, the code is like following
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('./sw.js').then(function(registration) {
// Registration was successful
console.log('Service Worker registration successful with scope: ', registration.scope);
// console.log('Service Worker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
The 404 error keeps pop up in localhost also the deployed URL which I have no clue why, how to solve this?
ServiceWorker registration failed: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
Thanks
Solutions (UPDATE) -
Include app.use('/', routes) ,or wherever the service-worker file at into index.js file.
you could use the full url path for the registration for example:
navigator.serviceWorker.register('ScriptsFolder/subFolder/sw.js')
The only way I have found to solve the TypeError issue when starting a nodejs service worker is to put the service worker script in the root directory of your application, in my case the root of my Amazon EC2 web server.
Wish the error message was more descriptive, TypeError is not terribly helpful. But this fix worked for me.

Nodejs error has no traceback

I'm somewhat new to nodejs.
Using express / npm.
Once i hit '/' from my browser, I get this in output:
[TypeError: Object #<Object> has no method 'push']
No line numbers, no traceback, nothing.
I need to be able to fix this error, and to do that I need to know what file / line # this occurred.
How do I get nodejs to output a traceback?
First, add an express error handler, which is middleware expecting 4 arguments:
app.use(function (error, req, res, next) {
console.error(error.stack);
});
Make sure to put the above code at the very end of your middleware stack after all your normal middleware and route handlers are defined.
If that doesn't get you your stack trace, catch process-level uncaught exceptions:
process.on("uncaughtException", function (error) {
console.error(error.stack);
});
And one final tip would be run your app under the debugger with node --debug=3001 app.js, connect to it with node-inspector, open the debugger in chrome, enable "stop on exceptions", then trigger the error. The debugger will take you to the line where the exception occurs.

Behavior in node 0.8.15 and node 0.10.26 - (Can't set headers after they are sent)

I was using Web Application which uses nodejs as backend Web Server, It was running fine as long as I was using node version 0.8.X, when I switched to recent node version 0.10.26, then the app is throwing error in below:
res.redirect('/path/to/page')
node_modules/redis/index.js:523
throw err;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
Can you please let me know why this throws error in 0.10.26?
With regards,
-M-
This is because you sent 2 times header Example
res.send("foo");
res.send("bar");
You can debug this like that:
app.use(function(req, res, next) {
res.on('header', function() {
console.trace('HEADERS GOING TO BE WRITTEN');
});
next();
});

Resources