멈멈-토이프로젝트(next.js)2
검색 창
순9
2024. 9. 25. 10:34
728x90
api라우트를 사용
에러
POST http://localhost:3000/api/community-search-api 405 (Method Not Allowed)
서버가 클라이언트에서 요청한 HTTP 메서드를 허용하지 않음을 의미
검색은 GET이라고 생각 해서 api를 GET으로 사용 했는데
fetch(`/api/community-search-api?search=${search}`, {}
URL 파라미터를 통해 검색어를 전달 해야한다고 하는데
내가 만들어 놓은 라우터 구조 와 달라 데이터를 제대로 가져 오지 못할거 같음
POST로 변경
사용 했던 api하고 크게 다른 점은 없다
수파베이스에서의 sql쿼리문을 수정을 수정
let { data, error } = await supabase
.from("community")
.select("*")
.ilike("content", `%${search}%`);
ilike 사용 해서 content에서 search가 있으면 출력
주소를 아래 처럼 만들기
http://localhost:3000/main/community?q=%%%
const [search, setSearch] = useState(""); // 검색할 단어 담는 상태
const handleSerch = () => {
router.push(`/main/community?q=${search}`)
try {
fetch("/api/community-search-api", {
method: "POST",
body: JSON.stringify({ search: search }),
})
.then((response) => {
if (!response.ok) {
throw new Error("검색 하지 못 했습니다.");
}
return response.json();
})
.then((data) => {
console.log(data.message);
setSearchData(data.data); //검색한 후의 결과를 담는 상태
});
} catch (error) {}
};
검색 버튼 클릭시
1. 해당 주소로 이동
2. api 실행
3. 실행 되어서 나온 데이터 setSearchData에 전달