버글버글
[React] Proxy수동설정, axios(get, post) 본문
반응형
1. VS code의 터미널에서 proxy-middleware 설치
npm install http-proxy-middleware
2.'setupProxy.js' 파일 생성
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/auth/register', // /auth/register을 사용 했을때, 아래 target으로 우회(?)
createProxyMiddleware({
target: 'http://123.0.0.0:포트번호', // 사용할 주소
changeOrigin: true,
})
);
};
- setupProxy는 설정하면 꼭 서버 재 시작을 해줘야 한다.
- 터미널에서 ctrl + c 를 누르면 서버 종료, 다시 npm start를 해주면 된다.
3. App.js에는 따로 setupProxy를 import 해줄 필요가 없다. (자동으로 실행됨)
- axios를 설치해준다.
npm install axios
- get 방식
import React, { useState } from 'react';
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import './App.css';
import axios from 'axios';
function App() {
return (
<Box>
<Button
variant="outlined"
onClick={() => { axios.get('URL') // setupProxy.js 에서 사용한 url
.then((result) => {
console.log(result.data);
})
.catch((error) => {
console.log(error) })
}}
>get</Button>
</Box>
);
}
export default App;
- post 방식 (1) (값을 직접 넣어주는 방식)
import React, { useState } from 'react';
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import './App.css';
import axios from 'axios';
function App() {
return (
<Box>
<Button
variant="outlined"
onClick={() => { axios.post('/auth/register', {
userId: "test2", // 값을 임의로 넣어줌
userPw: "1234", // 값을 임의로 넣어줌
userNm: "테스트"
})
.then((result) => {
console.log(result.data);
})
.catch((error) => {
console.log(error) })
}}
>(post)</Button>
</Box>
);
}
export default App;
- post 방식 (2) (input에 값을 받아오는 방식)
import React, { useState } from 'react';
import myLogo from './ussmLogo.jpg';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Box from '@mui/material/Box';
import './App.css';
import theme from "./theme";
import axios from 'axios';
function App() {
// 1. Login 정보
const [values, setValues] = useState({
idBox: "",
pwBox: "",
});
// 2. Login 정보
const handleChange = (e) => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
// 3. Login 이벤트
function handleSubmit(e) {
if(values.idBox === "") {
e.preventDefault();
alert("아이디를 입력해주세요.");
} else if (values.pwBox === "") {
e.preventDefault();
alert("비밀번호를 입력해주세요.");
} else if (values !== "" && values !== ""){
alert(values.idBox + "님 환영합니다.");
e.preventDefault();
axios.post('auth/login', {
userId: values.idBox, // idBox의 값 받아옴
userPw: values.pwBox, // pwBox의 값 받아옴
})
.then((result) => {
console.log(result.data) // 결과값 출력
})
} else {
e.preventDefault();
alert("로그인에 실패하였습니다.");
}
}
return (
<Box>
<ThemeProvider theme={theme}>
<form onSubmit={handleSubmit}>
<Box className="outBox">
<Box className="middleBox">
<Div>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<TextField
type="text"
name="idBox"
label="Id *"
margin="normal"
onChange={handleChange}
fullWidth
></TextField>
<TextField
type="password"
name="pwBox"
label="Password *"
margin="normal"
onChange={handleChange}
fullWidth
></TextField>
<Button
variant="outlined"
fullWidth
type="submit"
>
LOGIN
</Button>
</Div>
</Box>
</Box>
</form>
</ThemeProvider>
</Box>
);
}
export default App;
반응형
'React > react 공부기록' 카테고리의 다른 글
[React] 프로젝트 title / favicon(파비콘) 변경 (0) | 2023.04.19 |
---|---|
[React] 프로젝트 배포하기 (0) | 2023.04.17 |
[React] Cookie에 정보저장하기 (2) | 2023.04.13 |
[React] localStorage에 token 저장하기 (feat.JWT) (0) | 2023.04.12 |
[React] VS code에서 개발하기 ( + mui 사용하기) (0) | 2023.03.30 |