Thomas Johansen
Thomas Johansen

Reputation: 15258

How can I send JSON with ExpressJS as UTF-8?

I've been struggling with a new web app I'm making. In previous situations I cannot recall to have encountered this issue. I'm testing with a very simple piece of code.

var jsonToSend = {hello: "woørld"};
app.get('/someUrl', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(jsonToSend);
}

Output is: {"hello":"Woørld"} with Content-Type:application/json; charset=utf-8 in the network tab. I also tried various attempts with JSON.stringify and adding charset to setHeader, though it seems to be right in the network tab. How can I make sure the data is correctly encoded from the server?

I use WebStorm and I checked file encoding to be UTF-8.

Upvotes: 1

Views: 1682

Answers (2)

Bruno Farina
Bruno Farina

Reputation: 31

Try using res.set({ 'content-type': 'application/json; charset=utf-8' });:

var jsonToSend = {"\"hello"\": "\"woørld"\"};
app.get('/someUrl', function(req, res) {
  res.setHeader('Content-Type', 'application/json');

  res.set({ 'content-type': 'application/json; charset=utf-8' });

  res.send(jsonToSend);
}

Upvotes: 1

Thomas Johansen
Thomas Johansen

Reputation: 15258

I realized that the issue had to be towards my IDE. So this answer would target those of you who are using WebStorm:

I had previously started a project on my windows computer which converted my source files to windows-1252 encoding instead of utf-8. Make sure to do Preferences > File Encoding and set all encoding to UTF-8 and convert old files. The file encoding is also marked in the settings view.

Upvotes: 1

Related Questions