I have implemented a download file feature on my Angular-based client and node.js backend based on the following solution: https://stackoverflow.com/a/20904398/1503142. In general this works, but sometimes I receive a "SyntaxError: Unexpected number in JSON at position x" combined with a "TypeError: Cannot read propery 'messages' of undefined".
A few observations:
- Everything appears to be working on the node server-side, because I do always get a response at client. The error in question is reported by the client; no errors are reported by the server.
- The log file consists of a time stamp, then basic log information text. The text could contains ASCII characters
- Using Postman, the response works every time, which lends itself to the idea that it is the http$ code that might be having an issue with the response. Postman's response Header information indicates that the response is Content-Type->text/plain; charset=utf-8.
- I am using AngularJS v1.2.21 and Node v0.12.13
Here's the client-side code:
$http({
method: 'GET',
url: "/api/logging/logfiles/" + logFile,
headers: { 'Content-Type': 'text/plain;charset=utf-8' }
}).
success(function (data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:text/plain;charset=utf-8,' + encodeURIComponent(data),
target: '_blank',
download: logFile
})[0].click();
}).
error(function (data, status, headers, config) {
console.log('Hence my visit to StackOverflow!')
});
Here's the server-side code:
app.get('/api/logging/logfiles/:logfile', function (req, res, next) {
logDirectory = './log';
fs.readFile(logDirectory + "/" + req.params.logfile, 'utf8', function (err, data) {
if (err) {
res.send("Something broke!");
}
else {
res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
res.send(data);
}
});
});
I suspect that this is related to the contents of the log file. Since I've specified text/plain content, why would there be a JSON parsing error?