diff options
-rw-r--r-- | vnext/server/middleware/renderer.js | 48 | ||||
-rw-r--r-- | vnext/src/index.js | 11 |
2 files changed, 39 insertions, 20 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); + } + }); }); }; diff --git a/vnext/src/index.js b/vnext/src/index.js index 8064dd1f..5f3c262e 100644 --- a/vnext/src/index.js +++ b/vnext/src/index.js @@ -7,7 +7,16 @@ import './index.css'; const Juick = lazy(() => import('./App')); -const props = window.__PROPS__ ? JSON.parse(window.atob(window.__PROPS__)) : {}; +function fromBinary(encoded) { + const binary = window.atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return String.fromCharCode(...new Uint16Array(bytes.buffer)); +} + +const props = window.__PROPS__ ? JSON.parse(fromBinary(window.__PROPS__)) : {}; const JuickApp = () => ( <StrictMode> |