Reputation: 10669
I am using node.js with express. I read out data from MongoDB with Mongoose and deliver it the normal way with res.send(data)
. Unfortunately the delivering fails for some requests. Even so the header says the encoding is utf-8, it seems to be ANSI in some cases, causing the jsonp callback function to fail with an error.
You can reproduce the error at this page: http://like-my-style.com/#!single/9837034 . The jsonp call fails just on some products, most of them (also the ones with special chars) work fine.
How can I ensure, that a given String is encoded in utf-8 in node.js?
Upvotes: 11
Views: 30784
Reputation: 51
I think I got stuck in a similar issue and neebz solution worked but I had to put it in the right spot.
var req = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
**res.setEncoding(encoding='utf8');**
res.on('data', function(d) {
console.log(d);
});
});
In the node.js docs its documented as request.setEncoding() which might be an error because it needs to be called on the res object that is created by the request.
Upvotes: 1
Reputation: 4059
Have you tried:
res.send(data.toString("utf8"));
To ensure that your data is in utf8 and is not Buffer.
Upvotes: 10