Encoding problems in Node.js

  • The default data sent on the server is actuallyutf8Encoded content
  • But the browser doesn’t know you areutf8Encoded content
  • Without knowing the encoding of the server’s response, the browser will parse according to the default encoding of the current operating system
  • The default Chinese operating system isgbk
  • The solution is to tell the browser exactly what code I’m sending you
// require
/ / the port number

var http = require('http')

var server = http.createServer()

server.on('request'.function (req, res) {
 
res.setHeader('Content-Type'.'text/plain; charset=utf-8')
res.end('hello world')

server.listen(3000.function () {
  console.log('Server is running... ')})Copy the code



  • In the HTTP protocol,Content-TypeWhat is the type of data I’m sending you
  • It can be found in the API of Node.js Chinese website HTTP: nodejs.cn/api/http.ht…
    res.setHeader('Content-Type'.'text/plain; charset=utf-8')
Copy the code

Testing:

var http = require('http')

var server = http.createServer()

server.on('request'.function(req,res){
    res.setHeader('Content-Type'.'text/plain; charset=utf-8')
    res.end('hello world! ')
})



server.listen(3000.function(){
    console.log('Server is running... ');
})
Copy the code

The browser parses different content based on the path

  • text/plainIt’s plain text
  • Send thehtmlFormat the string, then also tell the browser I sent you istext/htmlFormatted content
var http = require('http')

var server = http.createServer()

server.on('request'.function (req, res) {

var url = req.url

  if (url === '/plain') {
    // text/plain is plain text
    res.setHeader('Content-Type'.'text/plain; charset=utf-8')
    res.end('hello world')}else if (url === '/html') {
    // If you're sending an HTML string, tell the browser I'm sending you text/ HTML as well
    res.setHeader('Content-Type'.'text/html; charset=utf-8')
    res.end('

Hello HTML I

') } }) server.listen(3000.function () { console.log('Server is running... ')})Copy the code
  • Request:localhost:3000/plain

  • Request:localhost:3000/html

  • Access to Baidu found that the response is a string, only the browser can parse out the recognition