๋ก๊ทธ์ธ ์ ํค๋์ ๋ด๊ธด Access-token์ ๋ฐ์์์ผ ํ๋๋ฐ headers ๊ฐ ๋ถ๋ฌ์์ง์ง ์๋ ์ค๋ฅ๊ฐ ์๊ฒผ๋ค.
const loginHandler = useCallback(async () => {
try {
const response: any = await fetch(Account.POST_SNS_LOGIN, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: authCode,
snsCode: "1110501",
phoneNumber: phone,
name: name,
}),
});
const data = await response.json();
console.log(data);
// if (response.ok) {
// // ์ฑ๊ณตํ๋ฉด ํ์ผ๋ก ๋ฆฌ๋ค์ด๋ ํธ
// router.push("/");
// } else {
// // ์คํจํ๋ฉด ์๋ฌ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
// }
} catch (error) {
console.error(error);
}
}, [router, authCode, phone, name]);
๋คํธ์ํฌ ํญ์์ ์ดํด๋ณด๋ ์๋ฒ์์ ์ ๋ณด๋ด์ฃผ๊ณ ์๋๋ฐ ๋ฐ์ง ๋ชปํ๊ณ ์๋๊ฑฐ์์
๊ทธ๋ฅ ๋ณ ์๊ฐ ์์ด fetch๋ฅผ ์ฌ์ฉํ๋๋ฐ,
๊ฒ์ํด๋ณด๋ fetch์์ ์ข ์ข ์ด๋ฐ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค๊ณ ํ๋๋ผ.
๊ทธ๋์ axios๋ก ๋ฐ๊ฟ ์ฃผ์๋ค
๐ป ํด๊ฒฐ
1. Axios
const loginHandler = useCallback(async () => {
try {
const response = await axios.post(
Account.POST_SNS_LOGIN,
{
code: authCode,
snsCode: "1110501",
phoneNumber: phone,
name: name,
},
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(response);
// if (response.ok) {
// // ์ฑ๊ณตํ๋ฉด ํ์ผ๋ก ๋ฆฌ๋ค์ด๋ ํธ
// router.push("/");
// } else {
// // ์คํจํ๋ฉด ์๋ฌ ํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
// }
} catch (error) {
console.error(error);
}
}, [router, authCode, phone, name]);
axios๋ก ๋ฐ๊พผํ ํ์ธํด๋ณด๋ ์ ๋ถ๋ฌ์ค๋ ๊ฒ์ ํ์ธํ ์ ์์๋ค ใ ใ
2. useMutation
const { mutate: loginMutate } = useMutation(
async () => {
const response = await axios.post(Account.POST_SNS_LOGIN, {
code: authCode,
snsCode: "1110501",
phoneNumber: phone,
name: name,
});
return response;
},
{
onSuccess: (response: any) => {
const data = response.data;
const headers = response.headers;
console.log(data, headers);
// router.push("/user/work/list");
},
onError: (error) => {
console.error(error);
},
}
);
react query์ธ useMutation์ผ๋ก ๋ง๋ฌด๋ฆฌํ๋น
์ด๋ ๋ง์ฐฌ๊ฐ์ง๋ก headers๋ฅผ ์์ฃผ ์~ ๋ถ๋ฌ์์!
fetch๋ ์ฌ์ฉ์ ์ง์ํด์ผํ ๊น? ใ ใ
https://developer.mozilla.org/en-US/docs/Web/API/Headers
Headers - Web APIs | MDN
The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.
developer.mozilla.org
https://stackoverflow.com/questions/48413050/missing-headers-in-fetch-response
Missing headers in Fetch response
I need to make a CORS post request. I need to use fetch because axios's response is already processed to json. But in fetch response, the headers is empty. But I don't think this is the server pr...
stackoverflow.com