How should I implement mobile phone detection in my real + express? I used mobile-detect to determine if it was mobile, but at first I implemented it using const md = new MobileDetect(window.navigator.userAgent), but I remembered it windowdidn’t exist when the server was loaded. The example in the express section should work, because this is the only place where I could access req, but how to transfer it in the response application, which will be used later?
UPDATE
// app.js
...
import { routes } from './routes';
import { match, RouterContext } from 'react-router';
import { renderToString } from 'react-dom/server';
...
const app = 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);
} else if (redirectLocation) { // we matched a ReactRouter redirect, so redirect from the server
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (props) { // if we got props, that means we found a valid component to render for the given route
const reducer = combineReducers(reducers);
const store = applyMiddleware(...middlewares)(createStore)(reducer);
...
const server = http.createServer(app);
const port = process.env.PORT || 3003;
server.listen(port);
server.on('listening', () => {
console.log('Listening on ' + port);
});
// client-render.js
import { routes } from './routes';
import { Router, browserHistory } from 'react-router'
ReactDOM.render(
<Provider store={store}>
<Router onUpdate={() => {scrollTop(); handleNotifs(store)}} routes={routes} history={browserHistory} />
</Provider>,
document.getElementById('app')
);
// routes.js
import AppComponent from './components/app';
import IndexComponent from './components/index';
...
const routes = {
path: '',
component: AppComponent,
childRoutes: [{
path: '/',
component: IndexComponent,
name: 'home'
}, {...}]
}
index source
share