Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //router.js
- import React from 'react'
- import { matchPath, StaticRouter } from 'react-router-dom';
- import { renderToString } from 'react-dom/server';
- import routes from './routes';
- import App from '../build-client/App.js';
- function GetMatchingRoute(url)
- {
- for (let i=0; i<routes.length; i++)
- {
- let route=routes[i];
- let match=matchPath(url, {path:route, exact:true});
- if (match)
- {
- return match;
- }
- }
- return null;
- }
- export default function router(req, res){
- const match=GetMatchingRoute(req.url);
- //const match = routes.reduce((acc, route)=>{return matchPath(req.url, {path: route, exact:true}) || acc}, null);
- if (!match)
- {
- res.status(404).send('page not found');
- return;
- }
- const context={}
- const router=(
- <div>
- hello world
- <StaticRouter context={context} location={req.url}>
- <App location={req.url}/>
- </StaticRouter>
- </div>
- )
- let html=renderToString(router);
- res.status(200).send(html);
- }
- //-------------------------------------------------------------------------------------------
- //app.js
- import React, { Component } from 'react';
- import Home from './Home'
- import Stuff0 from './Stuff0'
- import Stuff1 from './Stuff1'
- import {Switch, Route, Link} from 'react-router-dom'
- //import './styles/App.css';
- class App extends Component {
- render() {
- return (
- <div>
- <ul>
- <li><Link to="/">Home</Link></li>
- <li><Link to="/Stuff0">Stuff0</Link></li>
- <li><Link to="/Stuff1">Stuff1</Link></li>
- </ul>
- <Switch>
- <Route exact path="/" component={Home}>Home</Route>
- <Route path="/Stuff0" component={Stuff0}>Stuff0</Route>
- <Route path="/Stuff1" component={Stuff1}>Stuff1</Route>
- </Switch>
- </div>
- );
- }
- }
- export default App;
- //--------------------------------------------------------------------------------------------
- //server.js
- import express from 'express';
- import Path from 'path'
- import router from './router'
- const app = express();
- const port = 3500;
- app.get('*', router)
- app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement