Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #########################################################
- // index.js < server
- const express = require('express')
- const app = express()
- var cors = require('cors')
- var bodyParser = require('body-parser')
- app.use(cors())
- app.use(bodyParser.json())
- const LOGIN = 'uzivatel';
- const PASS = 'heslicko';
- const users = [{
- id: '1',
- name: 'uzivatel'
- }];
- /*
- app.get('*', (req, res) => res.send(`
- <html>
- <body>
- 123
- </body>
- </html>
- `))
- */
- app.get('/' , (req, res) => res.json({
- message: 'Hello worldi! z jsonu'
- }))
- app.get('/api/users', (req, res) => {
- res.json(users);
- })
- app.post('/api/add-user', (req,res) => {
- const { name } = req.body;
- users.push({
- id: users.length + 1,
- name
- });
- res.json(users)
- console.info(users)
- });
- app.post('/api/check-login', (req, res) => {
- const { username, password} = req.body;
- res.json({
- valid:username === LOGIN && password === PASS
- })
- })
- app.listen(3001, () => console.log('Example app listening on port 3001'))
- ################################################
- //Client app.js
- import React, { Component } from 'react';
- import './App.css';
- class App extends Component {
- state = {
- users:[],
- name:'',
- isAdmin: false,
- }
- async componentDidMount(){
- const response = await fetch('http://localhost:3001/api/users')
- const users = await response.json();
- this.setState({
- users
- });
- }
- addUser = async () => {
- const response = await fetch('http://localhost:3001/api/add-user', {
- method: 'POST',
- headers: {
- "Content-Type": "application/json; charset=utf-8",
- },
- body: JSON.stringify({
- name: this.state.name
- })
- })
- const users = await response.json();
- console.info(users)
- this.setState({
- users
- });
- }
- changeName = (e) => {
- this.setState({
- name: e.target.value
- })
- }
- checkCredentials = async () => {
- const response = await fetch('http://localhost:3001/api/check-login', {
- method: 'POST',
- headers: {
- "Content-Type": "application/json; charset=utf-8",
- },
- body: JSON.stringify({
- username: 'uzivatel',
- password: 'heslicko',
- })
- });
- const data = await response.json();
- this.setState({
- isAdmin:data.valid
- })
- }
- render() {
- const { users, name, isAdmin } = this.state;
- return (
- <div className="App">
- {users.map((user) => <div key={user.id}> {user.name}</div>)}
- <input type="text" value={name} onChange={this.changeName}/>
- <button onClick={this.addUser}>Pridej uživatele</button> <br/>
- <button onClick={this.checkCredentials}>Check Credentials</button>
- {isAdmin ? 'Je to admin' : ''}
- </div>
- );
- }
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement