Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Last active October 23, 2023 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms/43084736e76a58cef3124000823bcd9f to your computer and use it in GitHub Desktop.
Save xgqfrms/43084736e76a58cef3124000823bcd9f to your computer and use it in GitHub Desktop.
Node.js Express.js charset UTF-8

for who use the express.js server

UTF-8

Node.js Express.js charset UTF-8

charset=utf-8

'CharacterEncoding': 'UTF-8'

app.get('/sse', (req, res) => {
  res.writeHead(200, {
    // 'Content-Type': 'image/jpg',
    // 'Content-Type': 'image/png',
    // 'Content-Type': 'application/json',
    // 'Content-Type': 'text/event-stream',
    'Content-Type': 'text/event-stream; charset=utf-8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    // 'Access-Control-Allow-Origin': "*",
    // 'CharacterEncoding': 'UTF-8',
    // 'Accept-Encoding': 'UTF-8',
  });
  // response.setContentType("text/event-stream");
  // response.setCharacterEncoding("UTF-8");
  let i = 0;
  let uid = setInterval(() => {
    console.log(`i`, i);
    if(i < 10) {
      i++;
      const data = convertImageToBase64URL("./public/test.png");
      console.log(`SSE ${i}`, data.slice(0, 100));
      // ❌
      // res.write(data);
      // event id `lastEventId` ✅
      const id = 2023;
      res.write(`id: ${id}\n`);
      // event type `message` \n
      // event data `data` \n\n
      // res.write(`event: message\n`);
      // custom event type `custom_message`\n ✅
      res.write(`event: custom_event_message\n`);
      res.write(`data: ${data}\n\n`);
    } else {
      clearInterval(uid);
    }
  }, 3000);
});
// http://localhost:3000/sse

![image](https://github.com/nodejs/node/assets/7291672/24775c3b-bd27-412b-b955-933722a3079d)

![](https://user-images.githubusercontent.com/7291672/277396988-24775c3b-bd27-412b-b955-933722a3079d.png)

refs

nodejs/node#17390 (comment)

https://stackoverflow.com/questions/17872789/node-js-express-how-do-i-set-response-character-encoding

@xgqfrms
Copy link
Author

xgqfrms commented Oct 23, 2023

How to fix EventSource onmessage not working in JavaScript All in One

SSE: Server-Sent Events / 服务端推送

作者:xgqfrms
链接:https://www.cnblogs.com/xgqfrms/p/17783689.html
来源:https://www.cnblogs.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
©xgqfrms 2012-2023
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment