1

Postman Screenshot of dot net core API

Postman fetches the data from my dot net core API but I cannot get the data in React native using the same API. I tried everything like changing port number etc.

React Native API Request

useEffect(() => {
    const getData= async () => {
     try {
        const response = await axios.get('http://10.0.2.2:54669/DoctorMaster/Getalldoctorssearch/1062');
        setAppointments(response.data);
        setIsLoading(false);
        console.log(response.data);
       
        
       
     } catch (error) {
       console.log(error);     
       
     }
    }
    getData()
  }, [setAppointments, setIsLoading]);
Raja
  • 33
  • 1
  • 7
  • Please, share the code of your attempts to retreive data in react native app. What means can't get the data? Any errors? – Sergey Nazarov Apr 26 '22 at 10:10
  • i shared my code in question.and the error is bad request 400 – Raja Apr 26 '22 at 10:13
  • Are you running your app in docker? Why you send request to localhost in postman? – Sergey Nazarov Apr 26 '22 at 10:20
  • No, I'm not running in docker. I'm just running core API in local that is why I call it in localhost and it works well in postman but not in react native – Raja Apr 26 '22 at 10:24
  • Ok, I took the point. When I'm doing that in react native, I'm using [ngrok](https://ngrok.com) proxy to make my server api public. Ngrok runs proxy and gives you public endpoint which leads to your localhost on selected port. Then set up public endpoint in your react native app to access api. – Sergey Nazarov Apr 26 '22 at 11:00
  • do I need to install ngrok as an extension? because ngrok extension is not available in vs 2022 enterprise – Raja Apr 26 '22 at 12:53
  • No. You can download ngrok and run it in a separate process. – Sergey Nazarov Apr 26 '22 at 15:21

4 Answers4

0

Please follow the below structure

fetch(
  "url"
  {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: "Bearer " + JSON.parse(token),
    },
  }
)
  .then((response) => response.json())
  .then((responseJson) => {
    // Handle response here
  })
  .catch((error) => {
    console.error(error);
  });
S.Hashmi
  • 485
  • 1
  • 8
  • 29
0

Be aware that React Native refuses HTTP requests instead of HTTPS requests by default:

To handle HTTP requests in Android see this post

To handle HTTP requests in iOS see this post

0

You are trying to fetch data from localhost which your mobile device won´t be able to fetch the url. You need to publish your API on a Web Server, and then you will be able to fetch the data

0

Solution: All of the answers did not work for me, I used a visual studio extension called Conveyor by keyoti to solve the issue, this extension allow me to use the API outside of localhost, it will show you the remote URL, use that url to call API from your mobile application

Raja
  • 33
  • 1
  • 7