Say I got:
app.get('/json', function(req, res) { res.set({ 'content-type': 'application/json' }).send('{"status": "0"}'); });
I'm trying to send the response as UTF-8 with the following with no success:
app.get('/json', function(req, res) { // From Node.js Official Doc // http://nodejs.org/api/http.html#http_http_request_options_callback res.setEncoding('utf8'); res.set({ 'content-type': 'application/json' }).send('{"status": "0"}'); });
What is the correct way to set character encoding in Express?
Overview. In this guide, you can learn how to enable or disable the Node. js driver's UTF-8 validation feature. UTF-8 is a character encoding specification that ensures compatibility and consistent presentation across most operating systems, applications, and language character sets.
send() Send a string response in a format other than JSON (XML, CSV, plain text, etc.). This method is used in the underlying implementation of most of the other terminal response methods.
setHeader('Content-Type', 'text/html'); this line will set the format of response content o text/html. write() function method on response object can be used to send multiple lines of html code like below. res. write('<html>'); res.
You will probably want to explicitly add a charset to the end of your content-type string if you find it's not being set already by Express:
res.set({ 'content-type': 'application/json; charset=utf-8' });
The charset is not always set automagically and does need to be set to work correctly everywhere (i.e. with all browsers and all ajax libraries) or you can run into encoding bugs.
In Express 4.x specifically I've found that depending on the object you trying to return, it normally automatically returns with content-type: application/json; charset=utf-8
when you call res.json(someObject)
, however not always.
When calling res.json()
on some objects it can return content-type: application/json
(i.e. without the charset encoding!). I'm not actually sure what triggers this, other than it's something about the specific object being returned.
I've only noticed it because of automated tests which explicitly checked the headers and found it was missing the charset declaration on some responses (even though the content-type was still application/json
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With