Advertisement
Qpel

3 prakt

Nov 13th, 2019
447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. index:
  2. import React,{Component} from 'react';
  3. import ReactDOM from 'react-dom';
  4. import App from './App';
  5.  
  6. ReactDOM.render(
  7.   <App />,
  8.   document.getElementById('app')
  9. );
  10.  
  11.  
  12.  
  13. userapicontroller:
  14.  
  15.  
  16. import React,{Component} from 'react';
  17.  
  18. class UserApiController {
  19.     constructor(){
  20.         this.getUsers = this.getUsers.bind(this)
  21.     }
  22.     _usersList(){
  23.         return[
  24.             {id: 1, name: 'Jonas', surname: 'Grybas'},
  25.             {id: 2, name: 'Ernestas', surname: 'Arlauskas'}
  26.         ]
  27.     }
  28.  
  29.     getUsers(req, res, next){
  30.         const users = this._usersList()
  31.         return res.json(users)
  32.     }
  33. }
  34.  
  35.  
  36.  
  37. module.exports = UserApiController
  38.  
  39. app:
  40.  
  41.  
  42. import React,{Component} from 'react';
  43.  
  44. class App extends Component {
  45. constructor(props){
  46.     super(props)
  47.     this.onHandleUsers = this.onHandleUsers.bind(this)
  48.     this.state = {
  49.         isLoaded: false,
  50.         users: []
  51.     }
  52. }
  53.  
  54. onHandleUsers() {
  55.     fetch("http://localhost:3000/api/users")
  56.     .then(res => res.json())
  57.     .then(result => {
  58.         this.setState({
  59.             isLoaded: true,
  60.             users: result
  61.         })
  62.     })
  63.     .catch(e => console.log(e))
  64. }
  65.  
  66. render() {
  67.     return (
  68.         <div>
  69.             <button onClick={this.onHandleUsers}>Gauti vartotojus</button>
  70.         <ul>
  71.             {
  72.                 this.state.isLoaded && this.state.users.map(item => {
  73.                     return (
  74.                         <li>Vardas: {item.name}, pavarde: {item.surname}</li>
  75.                     )
  76.                 })
  77.             }
  78.         </ul>
  79.         </div>
  80.     )
  81. }
  82.  
  83. }
  84.  
  85. export default App
  86.  
  87.  
  88.  
  89.  
  90. routes:
  91.  
  92. import React,{Component} from 'react';
  93.  
  94.  
  95. const UserApiController = require('./controllers/UserApiController')
  96. const userApiController = new UserApiController()
  97.  
  98. module.exports = (app) => {
  99.     app.get('/', (req,res) => {
  100.         res.render('home')
  101.     })
  102.     app.get('/api/users', userApiController.getUsers)
  103. return app
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement