Fetch Api:Can not get data from localhost
Asked Answered
T

2

5

I have been trying to create an android app using nativescript.I am using fetch module to get response from my server.When I am trying to get response from httpbin.org/get ,it is OK.But when I am trying to get response from my local server,I am getting Network Request Failed. error.

Sending to httpbin.org/get-

return fetchModule.fetch("https://httpbin.org/get").then(response => { return response.text(); }).then(function (r) {
        console.log(r);
    }, function (e) {
            console.log(e);
        }); 

Sending to localhost:8000/api-

return fetchModule.fetch("http://localhost:8000/api").then(response => { return response.text(); }).then(function (r) {

       console.log(r);

}, function (e) {

        console.log(e);
    });

When I try to get response from localhost:8000/api in pure node.js via the request module.It worked fine.But now,I don't to know how to solve this in nativescript using fetch module.

Tincal answered 9/10, 2016 at 21:13 Comment(4)
Are you sure you have internet connection on mobile?Wake
Dont use localhost as localhost point to local device in this case your mobile which isn't server. Check on your pc what is IP and change localhost for IPAxinomancy
Why Internet Connection? I am using AVD of Android Studio.Tincal
See this answer https://mcmap.net/q/64119/-how-to-connect-to-my-http-localhost-web-server-from-android-emulator/3284355 localhost refers to the device(emulator) not to the IP of computer the emulator is running on.Moisture
A
9

Instead, localhost (usually 127.0.0.1) use 10.0.2.2 (if using AVD emulator)

10.0.2.2  - Special alias to your host loopback interface 
(i.e., 127.0.0.1 on your development machine)

For GenyMotion emulator the loopback address is 10.0.3.2

Assyria answered 10/10, 2016 at 13:3 Comment(4)
Like this- 10.0.2.2/api Or 10.0.2.2:8000/api like this?Tincal
Please help me here too superuser.com/questions/1449269/…Radiotelegraph
@user145959 you should use https://10.0.2.2 instaed http://localhost ... The IP address 192.168.x.x (indicates an address in the local network) has nothing to do with the loopback address so I am not sure why are you trying to use it in the first place.Assyria
@NickIliev: I changed my code like this export const baseURL = "https://10.0.2.2:3000"; but didn't work. I updated my questionRadiotelegraph
D
0

Emulator API Path:- http://10.0.2.2:5000. Like Your API Local Path Is http://198.168.1:5000/api or http://localhost:5000/api Then Replace With http://10.0.2.2:5000/api And Port Address Is Same Like As Your Local API Port.

Path- App_resources/Android/src/main/AndroidManifest.xml :-

android:usesCleartextTraffic="true" Add in application tag

Donaldson answered 8/1, 2021 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.