-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[React] React 로 서버와 통신하는 방법 #57
Comments
|
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
|
//클라이언트 POST API 요청
axios.post('http://localhost:3000/api/users/add', {
id: 4,
name: '개발이 취미인 사람',
})
//성공시 then 실행
.then(function (response) {
console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
console.log(error);
});
//서버 소스 코드
//임시 데이터
const users = [
{ id: 1, name: "유저1" },
{ id: 2, name: "유저2" },
{ id: 3, name: "유저3" }
];
/**
* @path {POST} http://localhost:3000/api/users/add
* @description POST Method
*
* POST 데이터를 생성할 때 사용된다.
* req.body에 데이터를 담아서 보통 보낸다.
*/
app.post("/api/users/add", (req, res) => {
// 구조분해를 통해 id 와 name을 추출
const { id, name } = req.body
//concat 함수는 자바스크립트에서 배열 함수이다. 새로운 데이터를 추가하면 새로운 배열로 반환한다.
const user = users.concat({id, name});
res.json({ok: true, users: user})
}) |
nodejs + express / react, axios / javascript |
리액트에서 라우팅을 담당하는 경우서버에서도 라우팅을 담당해줄 수 있고 (server.js에 추가)
app.get('*', function (요청, 응답) {
응답.sendFile(path.join(__dirname, '/react-project/build/index.html'));
}); |
리액트로 프론트엔드를 만들 경우 개발흐름예를 들어서 DB에서 글목록 데이터를 꺼내서 HTML로 보여주고 싶은 경우
리액트는 페이지가 index.html 하나만 있기 때문에 |
그리고 nodejs 서버파일엔 const 여러개 모여있는 곳 하단에 app.use(express.json());
var cors = require('cors');
app.use(cors()); 이 코드 넣고 시작하셔야 리액트와 nodejs 서버간 ajax 요청 잘됩니다. |
1-1. AJAX (Asynchronous Javascript And XML) |
# axios VS Fetch API |
Fetch()는 body 프로퍼티를 사용하고, axios는 data 프로퍼티를 사용합니다. 출처: https://koras02.tistory.com/48 [Koras02코딩웹:티스토리] |
axios는 HTTP 통신간에 요구사항을 Compact한 패키지로써 사용하기 쉽게 구성되어 있다. Axios는 운영환경에 따라서 브라우저간 XMLHttpRequest 객체 또는 Node.js의 HTTP API를 사용한다. Axios 다운로드 |
React 에서 서버통신하기 .. feat.axios
Axios 설치 및 사용
프록시 서버는 서버와 클라이언트 사이에서 요청을 허용/거부하는 역할을 수행해 Access-Control-Allow-Origin : *의 헤더를 담아 응답해준다고 한다. 중간 단계가 하나 더 생기는 것이기 때문에 속도가 느려지는 단점이 있다.
The text was updated successfully, but these errors were encountered: