32

How do I get UTF-8 support on my API? At the moment, a string outputs like this:

name: "John D�m"

Instead of:

name: "John Döm"

Checkout app.js below:

var express = require('express'),
    driver = require('./driver');

var app = express();

app.configure(function () {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

app.get('/drivers', driver.findAll);

app.listen(3000);
console.log('Up: http://127.0.0.1:3000/');
4
  • 3
    All strings in JS are UTF8 unless explicitly set to something else, so it is hard to say where your error would be coming from. What does driver do? The code you've provided is standard boilerplate and doesn't really help. Commented Apr 28, 2013 at 20:21
  • driver grabs all drivers from a mongoDB and prints all data out. See link here: xn--billstrm-t4a.se:1337 Commented Apr 28, 2013 at 20:23
  • @loganfsmyth driver = require('./driver'); Is pretty much the same as this one: gist.github.com/ccoenraets/3819468#file-wines-js Commented Apr 28, 2013 at 20:24
  • My guess would be that the data in your DB is not UTF8. How did you populate the DB? Commented Apr 28, 2013 at 20:40

3 Answers 3

49

Hook into you response generator or create a middleware that does the following:

res.setHeader("Content-Type", "application/json; charset=utf-8");

Otherwise the browser displays the content in it's favorite encoding.

If this doesn't help you DB is probably in the wrong encoding.

For older node.js versions use:

res.header("Content-Type", "application/json; charset=utf-8");
Sign up to request clarification or add additional context in comments.

5 Comments

res.charset = 'utf-8' is the same thing, right? I find it cleaner
res.charset did not work for me (nodejs 0.10.8) but this json-style worked : pastebin.com/NwcVEAra
Is this answer still correct? ...I'm having a hard time in my code... I keep getting � marks...
@D.Tate answer is still correct. The 'utf-8' depends on the encoding of your datasource.
Hi, I do not use a DB and want to avoid using with writeHead but I get TypeError: res.header is not a functionerror. Then solved this problem with this: res.setHeader('content-type', 'text/html; charset=utf-8'); text/html part is about my code, it works with application/json
1

I can't solve this problem with setting content type. I solved this problem with encode function.

res.cookie('someCookie', someCookie, {
  encode: c => c,
});

For more information: express cookie

ExpressJS version: 4.16.4

Comments

-4

My problem solved with this:

res.writeHeader(200 , {"Content-Type" : "text/html; charset=utf-8"});

1 Comment

This could lead to problems, if you want to return content but an HTTP status code other then 200.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.