diff options
author | Vitaly Takmazov | 2022-10-29 22:15:00 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2023-01-13 10:37:58 +0300 |
commit | d7fd6bee3230a2d6f82d6d1575ddb2ad10a0d881 (patch) | |
tree | 4f5ed17d0cc6082874b6fa7856887fc13e52c526 /vnext/server/middleware/renderer.js | |
parent | 48b2365a3b56b8a56bed7a77d2832ea51b617d6c (diff) |
Encode strings correctly
Diffstat (limited to 'vnext/server/middleware/renderer.js')
-rw-r--r-- | vnext/server/middleware/renderer.js | 48 |
1 files changed, 29 insertions, 19 deletions
diff --git a/vnext/server/middleware/renderer.js b/vnext/server/middleware/renderer.js index f60aa23c..6cc0b61b 100644 --- a/vnext/server/middleware/renderer.js +++ b/vnext/server/middleware/renderer.js @@ -10,7 +10,17 @@ import { StaticRouter } from 'react-router-dom/server'; const path = require('path'); const fs = require('fs'); -const serverRenderer = async (req, res, next) => { +// convert a Unicode string to a string in which +// each 16-bit unit occupies only one byte +function toBinary(string) { + const codeUnits = new Uint16Array(string.length); + for (let i = 0; i < codeUnits.length; i++) { + codeUnits[i] = string.charCodeAt(i); + } + return Buffer.from(String.fromCharCode(...new Uint8Array(codeUnits.buffer))).toString('base64'); +} + +const serverRenderer = async (req, res) => { // point to the html file created by CRA's build tool const filePath = path.resolve(__dirname, '..', '..', 'dist', 'index.html'); @@ -33,29 +43,29 @@ const serverRenderer = async (req, res, next) => { const marker = '<div id="app">'; const data = htmlData.split(marker); - const propsData = `<script>window.__PROPS__="${Buffer.from(JSON.stringify(props)).toString('base64')}";</script>${marker}`; + const propsData = `<script>window.__PROPS__="${toBinary(JSON.stringify(props))}";</script>${marker}`; let didError = false; const { pipe } = ReactDOMServer.renderToPipeableStream( <StaticRouter location={req.baseUrl} context={routerContext}> <App {...props} /> </StaticRouter> - , { - onShellReady() { - res.statusCode = didError ? 500 : 200; - res.setHeader('Content-type', 'text/html'); - res.write(data[0]); - res.write(propsData); - pipe(res, { end: false }); - }, - onAllReady() { - res.write(data[1]); - res.end(); - }, - onError(err) { - didError = true; - console.log(err); - } - }); + , { + onShellReady() { + res.statusCode = didError ? 500 : 200; + res.setHeader('Content-type', 'text/html'); + res.write(data[0]); + res.write(propsData); + pipe(res, { end: false }); + }, + onAllReady() { + res.write(data[1]); + res.end(); + }, + onError(err) { + didError = true; + console.log(err); + } + }); }); }; |