- Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathserver.js
More file actions
Latest commit
45 lines (37 loc) · 1.33 KB
/
Copy pathserver.js
File metadata and controls
45 lines (37 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
importexpressfrom'express';
importReactfrom'react';
import{renderToString}from'react-dom/server';
import{match,RouterContext}from'react-router';
import{routes}from'./routes';
constapp=express();
app.use(express.static('public'));
app.set('view engine','ejs');
app.get('*',(req,res)=>{
// routes is our object of React routes defined above
match({ routes,location: req.url},(err,redirectLocation,props)=>{
if(err){
// something went badly wrong, so 500 with a message
res.status(500).send(err.message);
}elseif(redirectLocation){
// we matched a ReactRouter redirect, so redirect from the server
res.redirect(302,redirectLocation.pathname+redirectLocation.search);
}elseif(props){
// if we got props, that means we found a valid component to render
// for the given route
constmarkup=renderToString(<RouterContext{...props}/>);
// render `index.ejs`, but pass in the markup we want it to display
res.render('index',{ markup })
}else{
// no route match, so 404. In a real app you might render a custom
// 404 view here
res.sendStatus(404);
}
});
});
app.listen(3003,'localhost',function(err){
if(err){
console.log(err);
return;
}
console.log('Listening at http://localhost:3003');
});