R
R
Richard Hendrix2018-04-10 23:16:36
Node.js
Richard Hendrix, 2018-04-10 23:16:36

How to render in node.js - JSX (react)?

Test server code

const http = require('http');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const StaticRouter = require('react-router').StaticRouter;

const Express = require('express');
const app = new Express();

const server = new http.Server(app);

app.set('view engine', 'ejs');
app.use('/dist', Express.static('dist'));

app.get('*', (req, res) => {

    const context = {};

    const html = ReactDOMServer.renderToString(
        <StaticRouter location={req.url} context={context}>
            <p>test</p>
        </StaticRouter>
    );

    if (context.url) {
        res.writeHead(302, {
            Location: context.url
        });
        res.end()
    } else {
        res.write(html);
        res.end()
    }
});

server.listen(3000, (err) => {
    if (err) {
        return console.error(err);
    }
    console.info('Server running on http://localhost:3000');
});

I am getting this error:
\test-server.js:19
        <StaticRouter location={req.url} context={context}>
        ^

SyntaxError: Unexpected token <
    at new Script (vm.js:51:7)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Richard Hendrix, 2018-04-11
@GeekT

I did this and still got a syntax error.5acdba0acd910492886248.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question