简体   繁体   中英

Incorrect utf-8 characters displayed in node.js, how to fix that?

I am a beginner in node.js and i tried to set up a HTTP server. I came from web Javascript and i know very little about node.js. I tried a code from nodejs.org, which worked, but when i tried characters like this "á" or "Š", it displayed incorrectly.

I tried using libraries like express.js, it fixed the problem, but i am vanilla - i don't like librariess and it proved difficult for me to even show different pages with different URLs.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Vítejte na mojí webové stránce!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

The result: VĂtejte na mojĂ webovĂ© stránce!

What @thomas said: You need to send a header to the browser to tell it which character set to use rendering your text.

res.setHeader('Content-Type', 'text/plain; charset=utf-8');

Some browsers on some host machines may sometimes do the right thing rendering text if you don't do this. But you should not rely on that chance, especially for plain text.

Pro tip : The entire point of nodejs as a platform is to organize your use of good libraries. Node is not a block of wood from which you carve a sculpture, it's a set of lego blocks: really good lego blocks. There's no point in avoiding libraries unless you want to reinvent the flat tire. You can't avoid them: you use the http library already. (Yes, it's built in, but it's still a library.)

It's fine to learn by using minimal libraries. But if you want to actually serve rendered html or files from your file system, you need to use express.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM