반응형
저번시간에는 프론트에서 입력을 받고 server에서 출력을 해보았따.
이번에는 반대로 server에서 보내보자
먼저 server.js다
const express = require("express");
const app = express();
const port = 3001; // react의 기본값은 3000이니까 3000이 아닌 아무 수
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) =>{
res.send('혁이는 코딩 중!')
})
app.post("/idplz", (req,res)=>{
const serverid = req.body.plzid;
console.log(serverid);
const sendText = {
text : "열심히 코딩 중",
};
res.send(sendText);
});
app.listen(port, ()=>{
console.log(`Connect at http://localhost:${port}`);
})
res.send(보낼것)을 쓰면 된다.
App.js
import React, { Component } from 'react'
import './App.css';
export default class App extends Component {
state = {
id : "",
}
handleChange =(e)=>{
this.setState({
[e.target.name] : e.target.value,
});
}
submitId = ()=>{
const post ={
plzid : this.state.id,
};
fetch("http://localhost:3001/idplz", {
method : "post", // 통신방법
headers : {
"content-type" : "application/json",
},
body : JSON.stringify(post),
})
.then((res)=>res.json())
.then((json)=>{
this.setState({
id : json.text,
});
});
};
render() {
return (
<div>
<input onChange={this.handleChange} name ="id"/>
<button onClick = {this.submitId}>Submit</button>
<h1>{this.state.id}</h1>
</div>
)
}
}
res로 받은것을 json으로 변환하고 json.text을 this.state.id에 저장한다.
결과
반응형
'React' 카테고리의 다른 글
React - mysql연동하기, 연결 (데이터불러오기) (0) | 2020.10.17 |
---|---|
React - Mysql 연동하기, 연결(데이터 저장) (0) | 2020.10.17 |
React와 Express연동하기 1 (2) | 2020.10.15 |
React - SPA(Single Page Application)만들어보기 - 4. Modal창 만들기 (0) | 2020.10.15 |
React - SPA(Single Page Application)만들어보기 -3. 파비콘 및 타이틀바꾸기 (0) | 2020.10.11 |