-
6. React와 Express, MongoDB 연동하기 - Socket.io2018~2019/React.js 2018. 10. 6. 21:21
Socket.io
1. react-server
1-1) npm install socket.io
1-2) react-server/bin 삭제
1-3) react-server/app.js 수정
const createError = require('http-errors');const express = require('express');const path = require('path');const cookieParser = require('cookie-parser');const logger = require('morgan');require('dotenv').config();const webSocket = require('./socket');const indexRouter = require('./routes/index');const usersRouter = require('./routes/users');const connect = require('./schemas');const app = express();connect();app.set('views', path.join(__dirname, '../react-client/build'));app.set('view engine', 'jade');app.set('port', process.env.PORT || 8080);app.use(logger('dev'));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, '../react-client/build')));app.use('/', indexRouter);app.use('/users', usersRouter);app.use(function(req, res, next) {next(createError(404));});app.use(function(err, req, res, next) {res.locals.message = err.message;res.locals.error = req.app.get('env') === 'development' ? err : {};res.status(err.status || 500);res.render('error');});const server = app.listen(app.get('port'), () => {console.log(`${app.get('port')}번 포트에서 대기 중`);});webSocket(server);1-4) react-server/package.json 수정
"scripts": {"start": "babel-node app"},2. react-client
2-1) npm install socket.io-client
2-2) react-client/src/App.js 수정
import React, { Component } from 'react';import './App.css';import socketIOClient from 'socket.io-client';class App extends Component {constructor(props) {super();this.state = {users: [],name : '',age : '',};}componentDidMount() {this.getUser();const socket = socketIOClient('http://localhost:8080');socket.on('news', data => {console.log(data);socket.emit('reply', 'Hello, Node.js');});}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 => res.json()).then(res => this.getUser());document.getElementById('name').value = "";document.getElementById('age').value = "";}handleupdate = (e) => {e.preventDefault();const { id } = e.target;const name = prompt("바꿀 이름을 입력하세요.");if(!name) {return alert("이름을 입력해주세요.");}fetch(`/users/${id}`, {method: 'PATCH',body: JSON.stringify({name,}),headers: {'Accept': 'application/json','Content-Type': 'application/json'}}).then(res => this.getUser());}handledelete = (e) => {e.preventDefault();const { id } = e.target;fetch(`/users/${id}`, {method: 'DELETE',headers: {'Accept': 'application/json','Content-Type': 'application/json'},}).then(res => this.getUser());}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}<button id={user._id} onClick={this.handleupdate}>수정</button><button id={user._id} onClick={this.handledelete}>삭제</button></div>)}</div>);}}export default App;3. 결과
- npm start => http://localhost:3000/
1) react-server
2) react-client
'2018~2019 > React.js' 카테고리의 다른 글
MobX (0) 2018.10.14 Chat App with ReactJS, Socket.io #1 (0) 2018.10.07 5. React와 Express, MongoDB 연동하기 (4) UPDATE (0) 2018.10.06 4. React와 Express, MongoDB 연동하기 (3) DELETE (0) 2018.10.05 3. React와 Express, MongoDB 연동하기 (2) Create (0) 2018.10.04