Front End/React, ReactNative
reactNative axios get요청 보내기 localhost -> 192.168.0......
LoGinShin
2023. 11. 21. 02:08
반응형

node.js express를 사용해서
api를 작성 후 테스트해보려 했는데 사소한 문제가 발생했는데
원인파악이 힘들었는데 생각보다 당연한 문제여서 해결했던 경험을 공유합니다.
API code
//router로 get 요청받기
router.get('/', (req,res) => {
const responseObject ={
key: 'value',
key2: 'value2'
//costom
};
res.send(responseObject);
});
get 요청을 주소에 localhost로 지정하고 보내면 될 줄 알았는데
axios error이 계속 떠서 뭐가 문제인지 몰랐다.

// data get요청
const getData = async() =>{
const response = await axios.get('http://localhost:3000/')
.then(function (response) {
console.log(response.data);
})
.catch(function (error){
console.log(error);
});
}
문제의 코드입니다.
문제 없을 줄 았았는데 url을 적을 때에는 localhost를 참조할 때 일반적으로 발생하는 문제라고 합니다.
실제로 디바이스 자체를 가리키는데,
즉, 디바이스에서는 자체적으로 서버를 실행하지 않는 한 localhost에 접근할 수 없다고 합니다.
그래서 개발 중인 컴퓨터의 ip 주소 사용해야 하는데, 자신의 로컬 IP주소를 사용해서 API를 호출하면 문제가 해결될 수 있습니다. 예를 들어 , 로컬 IP 주소가 192.168.1.4라면, axios호출을
axios.get('http://192.168.1.4:3000')
이와 같이 수정하실 수 있습니다.
cmd를 켜고 ipconfig 입력해서 제 ip를 입력하니 해결됐습니다.
밑에와 같이 수정해서 해결했습니다.
// data get요청
const getData = async() =>{
const response = await axios.get('http://192.168....')
.then(function (response) {
console.log(response.data);
})
.catch(function (error){
console.log(error);
});
}

결론 : 핸드폰에서 localhost는 헨드폰 기기였다...
happy ending
728x90
반응형