Я пытаюсь преобразовать свое приложение из рендеринга на стороне клиента в рендеринг на стороне сервера. Я хочу передать реквизиты (роль пользователя) со своего сервера. js и получить доступ к нему на стороне клиента, чтобы я мог отобразить компонент в соответствии с ролью, данной пользователю.
Что я хочу сделать is:
- Отправка роли пользователя с сервера. js
- Доступ к реквизитам в приложении. js для получения этой роли
сервер. js
import fs from 'fs'
import express from 'express'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router-dom';
import App from '../src/App'
const PORT = 8090
const app = express()
const router = express.Router()
const serverRenderer = (req, res, next) => {
const context = {};
const ftRole = 'Admin';
<App /></StaticRouter>);
const appString = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context} basename={'/next.gir'}>
<App ftRole='Read'/>
</StaticRouter>
);
fs.readFile(path.resolve('./build/index.html'), 'utf8', (err, data) => {
if (err) {
console.error(err)
return res.status(500).send('An error occurred')
}
return res.send(
data.replace(
'<title>React App</title>',
`<title>NGIRRRRRRR</title>`
).replace(
'<div id="root"></div>',
`<div id="root">${appString}</div>`
)
)
})
}
router.use('^/$', serverRenderer)
router.use(
express.static(path.resolve(__dirname, '..', 'build'), { maxAge: '30d' })
)
app.use(router)
app.listen(PORT, () => {
console.log(`SSR running on port ${PORT}`);
})
index. js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import "./i18n";
import 'core-js/fn/object/assign';
import 'core-js/fn/promise';
import 'core-js/es6/array';
import 'core-js/es6/object';
import 'core-js/es6/symbol';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
//import 'core-js/es6/date';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import axios from "axios";
import properties from './config/properties';
import { BrowserRouter } from 'react-router-dom';
axios.defaults.headers.common['certData'] = properties.certificate;
ReactDOM.hydrate(
<BrowserRouter basename={'/next.gir'}>
<App/></BrowserRouter>, document.getElementById('root'));
serviceWorker.unregister();
Приложение. js
import React , { useState , useEffect} from "react";
import { BrowserRouter as Router, Route, Redirect , Switch} from "react-router-dom";
import routes from "./routes";
import withTracker from "./withTracker";
import "bootstrap/dist/css/bootstrap.min.css";
import "./shards-dashboard/styles/shards-dashboards.1.1.0.min.css";
import { useTranslation } from "react-i18next";
import MainSidebar from "./components/layout/MainSidebar/MainSidebar";
import DefaultLanguage from "./components/layout/MainNavbar/NavbarNav/DefaultLanguage";
import 'core-js/fn/object/assign';
import 'core-js/fn/promise';
import 'core-js/es6/array';
import 'core-js/es6/object';
import 'core-js/es6/symbol';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
//import 'core-js/es6/date';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import UserContext from "./config/UserContext";
import { Spinner } from 'react-bootstrap';
import { BrowserRouter } from 'react-router-dom';
// var block;
// var access = 'Admin'
var Authenticated = true;
class App extends React.Component {
constructor(props) {
super(props);
this.state ={
block:null,
access:'Read',
}
}
componentDidMount(){
if(this.props.ftRole === undefined)
{
return(
<div style={{ textAlign: 'center' }}>
<Spinner animation="grow" variant="primary" />
</div>)
}
else{
this.setState({
block:null,
access:this.props.ftRole,
})
}
}
componentWillReceiveProps(prevProps, prevState) {
if ((this.props.ftRole !== prevProps.ftRole) && (this.props.ftRole !== undefined)) {
this.setState({
block:null,
access:this.props.ftRole,
})
}
}
fakeAuth = {
isAuthenticated: Authenticated,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}
PrivateRoute({ ...rest }) {
return (
<Route
{...rest}
render={props =>
this.fakeAuth.isAuthenticated ? (
true
) : (
<Switch>
<Route
to={{
pathname: "/Useraccess",
state: { from: props.location }
}}
/>
</Switch>
)
}
/>
);
}
render(){
if(this.props.ftRole === undefined){
return(<Spinner/>)
}
else{
return(
<div>
<div>
{routes.map((route, index) => {
return (
<Route
key={index}
path={route.path}
exact={route.exact}
component={withTracker(props => {
return (
<route.layout {...props} >
<route.component {...props} />
</route.layout>
);
})}
/>
);
})}
</div>
<Route exact path="/" render={() => (
<Redirect to=""/>
)}/>
<MainSidebar user={this.state.access}/>
</div>
);
}
}
}
export default App;