[TIL] 2023-04-10 DAY17
GIT 주소
https://github.com/dowoo303/react-API
https://github.com/dowoo303/expressJS
- 오늘 배운것들
- react-icons-2
실제 Get요청 Post요청을 통해 Rest API를 사용(Axios-라이브러리)
오픈웨더 API(Weather.jsx) - get : https://openweathermap.org/
chat GPT(Chat.jsx) - post
- express
nodeJS 중에서도 ExpressJS 학습
- 각종 팁
- 비동기 방식이란 : 비동기처리 방식은 DB에서 데이터를 불러오거나 API에서 데이터를 불러오는 일과 같이 시간이 걸리지만 다 끝날 때 까지 마냥 기다리고 있기에는 비효율적인 상황을 효율적으로 해결하는 데 유용한 방식
- async=비동기, await=기다려라
- async문은 try와 catch을 감싼다.
- promise 객체 : 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타내기 위한 객체(대기, 이행, 거부)
- 렌더링 안에서 값이 있을때 없을때 구분해서 실행하는법은 삼항연산자를 사용한다.
- 글자 자르기 : substring(0,2) -> 0번째부터 2개 가져오기
- .env에 중요한 키들(API 키 등등)을 보관하고, .gitignore에 등록시켜 git에 중요한 정보가 올라가지않도록 해야한다.
- 설치 명령어 :
npm i react-icons- 사이트 : https://react-icons.github.io/react-icons
import { SiOpenai } from "react-icons/si";
function App() {
return (
<div className="bg-red-100 min-h-screen flex justify-center items-center">
<SiOpenai size={100} color="deeppink" />
<div className="ml-4 text-6xl">무엇이든 물어보세요.</div>
</div>
);
}
export default App;
개념
- REpresentational State Transfer의 약어입니다.
- 자원을 이름으로 구분해서 해당 자원을 주고 받는 모든 것을 일컫습니다.
- 자원의 이름과 전달 방식만으로 해당역할을 추론할 수 있습니다.
GET /movies (영화의 리스트를 가져옵니다.)
GET /movies/:id (특정 영화의 정보를 조회합니다.)
POST /movies (새로운 영화를 생성합니다.)
PUT /movies (영화의 정보를 업데이트 합니다.)
DELETE /movies (영화 데이터를 삭제합니다.)
Axios
- 설치 명령어 :
npm i axios- Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트이다.
- Axios 라이브러리는 promise 객체를 쉽고 편하게 만들기 위해 존재한다.
- Axios는 데이터를 포장을 해서 보내준다.
- Axios를 이용해서 Rest API를 사용해본다.
const onSubmitChat = async (e) => {
try {
// Enter키로도 검색 가능하도록 새로고침 방지
e.preventDefault();
if (isLoading) {
alert("검색중입니다 ...");
return;
}
if (!question) {
alert("질문을 입력해주세요.");
return;
}
// 로딩중 true
setIsLoading(true);
setContent("");
const response = await axios.post(
"https://holy-fire-2749.fly.dev/chat",
{
// question: question,
question, // 키, value 값, 이름이 모두 같으면 생략 가능
},
{
headers: {
Authorization: "Bearer BLOCKCHAINSCHOOL3", // 백엔드에서 이 값이 오지 않으면 값이 오지 않도록 설정되어 있음
},
}
);
if (response.status !== 200) {
alert("오류가 발생했습니다.");
setIsLoading(false);
return;
}
console.log(response);
setContent(response.data.choices[0].message.content);
// 로딩중 false
setIsLoading(false);
} catch (error) {
console.log(error);
// 로딩중 false
setIsLoading(false);
}
};
const getWeatherInfo = async () => {
try {
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_WEATHER_API}&units=metric`
);
if (response.status !== 200) {
alert("날씨 정보를 가져오지 못했습니다.");
return;
}
// 통과되면 실행
console.log(response.data);
setWeatherInfo(response.data);
} catch (error) {
console.error(error);
}
};
설치
새 폴더 생성 후
npm init
expressJS 설치 :npm install express --save
ExpressJS
- 개념
NodeJS의 등장으로 자바스크립트는 프론트 엔드 영역을 넘어, 백 엔드 영역까지 확장하게 되었습니다.
그 중에서도 ExpressJS를 공부하여 백 엔드는 어떻게 구성되어 있고 백 엔드와 프론트 엔드는 어떻게 소통이 이루어지는지 살펴보도록 하겠습니다.- 학습내용
react와는 다른 export, import 방법
백엔드 서버 만든 후, 요청 보내보기- 테스트 장소
insomnia(https://insomnia.rest/)
postman(https://www.postman.com/)
const express = require("express"); // import
const app = express();
const port = 3010;
app.get("/", (req, res) => {
res.send("Hello, Express!");
});
app.post("/", (req, res) => {
res.send("This is Post Request");
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
