If you're working on a project where you need to view any Javascript errors, but can't view the dev tools for some reason, then you can replace the standard Javascript error output with an ajax request to your server to log the problem.
1. Create a server to listen to your ajax requests
var http = require('http');
var querystring = require('querystring');
function processPost(request, response, callback) {
var queryData = '';
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
// kill the connection if data is too long - prevents server hanging
if(queryData.length > 1e6) {
queryData = '';
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
request.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
http.createServer(function(req, res) {
if(req.method === 'POST') {
processPost(req, res, function() {
console.log(req.post);
res.writeHead(200, {'Content-Type': 'text/plain' });
res.end();
});
} else {
console.log('GET', req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('hello');
}
}).listen(9876);
This will run on port 9876 and listens to post and get requests.
2. Send ajax requests on errors
Add the ajax function to your code, and replace the onerror and console functions.
// GET version
function somethingTerribleHappened(msg, url, line) {
var req = new XMLHttpRequest();
req.open('GET', 'http://[url]:9876?msg=' + encodeURIComponent(msg) + '&url=' + encodeURIComponent(url) + '&line=' + encodeURIComponent(line));
req.send();
}
// POST version
function somethingTerribleHappened(msg, url, line) {
var req = new XMLHttpRequest();
req.open('POST', 'http://[url]:9876');
var params = 'msg=' + encodeURIComponent(msg) + '&url=' + encodeURIComponent(url) + '&line=' + encodeURIComponent(line);
req.send(params);
}
// replace the standard error functions with your ajax
window.onerror = somethingTerribleHappened;
console.log = somethingTerribleHappened;
console.error = somethingTerribleHappened;
3. Run your server
node server.js > js-errors.log
When you visit your site, any Javascript errors or console messages will appear in your new log.