-
3. React와 Express, MongoDB 연동하기 (2) Create2018~2019/React.js 2018. 10. 4. 12:31
1. Create
1-1) react-client/src/App.js 수정
import React, { Component } from 'react';import './App.css';class App extends Component {constructor(props) {super();this.state = {users: [],name : '',age : '',};}componentDidMount() {this.getUser();}getUser = () => {fetch('/users').then(res => res.json()).then(users => this.setState({ users }));}handleChange = (e) => {this.setState({[e.target.name]: e.target.value});}handleClick = () => {const { name, age } = this.state;fetch('/users', {method: 'POST',body: JSON.stringify({name,age,}),headers: {'Accept': 'application/json','Content-Type': 'application/json'},}).then(res => this.getUser());document.getElementById('name').value = "";document.getElementById('age').value = "";}render() {return (<div className="App"><h1>Users</h1><p>이름 : <input id="name" name="name" onChange={this.handleChange}></input><br/>나이 : <input id="age" name="age" onChange={this.handleChange}></input><br /><button onClick={this.handleClick}>등록</button></p>{this.state.users.map(user =><div key={user._id}>{user.name} {user.age}</div>)}</div>);}}export default App;1-2) react-sever/route/user.js 수정
import express from 'express';import User from '../schemas/user';const router = express.Router();router.get('/', async (req, res, next) => {const users = await User.find({});res.json(users);});router.post('/', (req, res, next) => {const user = new User({name : req.body.name,age : req.body.age,});user.save().then((result) => {console.log(result);res.status(201).json(result);});});module.exports = router;1-3) 연동확인
- npm start => http://localhost:3000/
'2018~2019 > React.js' 카테고리의 다른 글
5. React와 Express, MongoDB 연동하기 (4) UPDATE (0) 2018.10.06 4. React와 Express, MongoDB 연동하기 (3) DELETE (0) 2018.10.05 now.sh 느릴 때 (0) 2018.10.02 2. React와 Express, MongoDB 연동하기 (1) Retrieve (0) 2018.10.02 1. React와 Node(Express) 연동하기 (1) 2018.10.02