forked from start-react/sb-admin-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
150 lines (136 loc) · 4.95 KB
/
Copy pathserver.js
File metadata and controls
150 lines (136 loc) · 4.95 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
// import expressGraphQL from 'express-graphql';
// import jwt from 'jsonwebtoken';
import React from 'react';
import ReactDOM from 'react-dom/server';
import UniversalRouter from 'universal-router';
import PrettyError from 'pretty-error';
import Html from './components/Html';
import { ErrorPageWithoutStyle } from './routes/error/ErrorPage';
import errorPageStyle from './routes/error/ErrorPage.css';
// import passport from './core/passport';
// import models from './data/models';
// import schema from './data/schema';
import routes from './routes';
import assets from './assets'; // eslint-disable-line import/no-unresolved
import { port, auth } from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
app.use(expressJwt({
secret: auth.jwt.secret,
credentialsRequired: false,
getToken: req => req.cookies.id_token,
}));
// app.use(passport.initialize());
//
// app.get('/login/facebook',
// passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
// );
// app.get('/login/facebook/return',
// passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
// (req, res) => {
// const expiresIn = 60 * 60 * 24 * 180; // 180 days
// const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
// res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
// res.redirect('/');
// }
// );
//
// Register API middleware
// -----------------------------------------------------------------------------
// app.use('/graphql', expressGraphQL(req => ({
// schema,
// graphiql: true,
// rootValue: { request: req },
// pretty: process.env.NODE_ENV !== 'production',
// })));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
let css = new Set();
let statusCode = 200;
const data = { title: '', description: '', style: '', script: assets.main.js, children: '' };
await UniversalRouter.resolve(routes, {
path: req.path,
query: req.query,
context: {
insertCss: (...styles) => {
styles.forEach(style => css.add(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len
},
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
render(component, status = 200) {
// console.log('inside render of UniversalRouter', component);
css = new Set();
statusCode = status;
data.children = ReactDOM.renderToString(component);
data.style = [...css].join('');
return true;
},
});
// console.log('outside render func of UniversalRouter with statusCode', statusCode);
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode);
res.send(`<!doctype html>${html}`);
} catch (err) {
// console.log('some error occured', err);
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
console.log(pe.render(err)); // eslint-disable-line no-console
const statusCode = err.status || 500;
const html = ReactDOM.renderToStaticMarkup(
<Html
title="Internal Server Error"
description={err.message}
style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle
>
{ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)}
</Html>
);
res.status(statusCode);
res.send(`<!doctype html>${html}`);
});
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}/`);
});
//
// Launch the server
// -----------------------------------------------------------------------------
/* eslint-disable no-console */
// models.sync().catch(err => console.error(err.stack)).then(() => {
// app.listen(port, () => {
// console.log(`The server is running at http://localhost:${port}/`);
// });
// });
/* eslint-enable no-console */