简体   繁体   中英

net::ERR_CONNECTION_REFUSED ionic

I'm developing an application using ionic , I could retrieve data from my webApi server and display them on the navigator with ionic serve but when I try to execute it on the emulator: ionic run android -l -c i get this error : net::ERR_CONNECTION_REFUSED

在此处输入图像描述

What is strange is that the $scope contains the required data and I could log them .

More than likely localhost on the Android device/emulator does not resolve to the IP of your development machine/server. Localhost probably points to the device/emulator itself. Can you hit the actual IP Address of your machine instead? Or can you host the web service somewhere in the cloud and try that?

Thanks, Dan

From your emulator (and the Ionic app is running in the emulator), http://localhost no longer refers to your computer, it refers to the emulated devise. Understanding this, http://localhost:26309/api/User/getAll/ is not a valid endpoint in your devise so the request fails.

To solve this you have two options:

First option is to create a simple proxy in your Ionic app. Edit your ionic.config.json as follows:

{
  "name": "appname",
  ...
  "proxies": [
    {
      "path": "/localhost",
      "proxyUrl": "http://localhost:26309"
    }
  ]
}

Now, when doing a request from your Ionic app, simply write /localhost/api/User/getAll/ and it should work.

Second option is to use the private IP of your computer as the endpoint domain. So instead of using http://localhost:26309 you can use http://192.168.XY:26309

Since the cordova app is loaded from the device file system, it has a different origin than the web api. The app tries to call the web api, but this is prohibited by the Same Origin Policy . To overcome this issue you need to enable CORS on your web api.

To enable CORS you need to install Microsoft.AspNet.WebApi.Cors NuGet package and use EnableCors attribute. For example:

using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
using WebApiServer.Models;

namespace WebApiServer.Controllers
{
    [RoutePrefix("databases")]
    [EnableCors("*", "*", "*")]
    public class DatabasesController : ApiController
    {
        [Route("")]
        [HttpGet]
        public IHttpActionResult Get()
        {
            var databases = new List<DatabaseCategory>()
            {
                new DatabaseCategory
                {
                    CategoryName = "Bases de datos relacionales",
                    Databases = new List<Database>()
                    {
                        new Database() { DatabaseName = "SQL Server" },
                        new Database() { DatabaseName = "Oracle" },
                        new Database { DatabaseName = "PostgreSQL" }
                    }
                },
                new DatabaseCategory
                {
                    CategoryName = "Bases de datos NoSQL",
                    Databases = new List<Database>()
                    {
                        new Database() { DatabaseName = "RavenDB" },
                        new Database { DatabaseName = "CouchBase" },
                        new Database { DatabaseName = "MongoDB" }
                    }
                }
            };
            return Ok(databases);
        }
    }
}

If the app running on a device (emulated or physical) calls http://localhost:26309/databases it tries to connect to port 26309 on the device itseft, not to the developer machine that is running the web api. So you receive ERR_CONNECTION_REFUSED , because no one on the device is listening on that port.

So instead of using http://localhost:26309 you should be using your developer machine ip address or a DNS name that resolves to it. For example http://192.168.8.162:26309 or http://yourMachine.yourDomain.com:26309 . But then you will hit another problem, your web api is running on the development web server IIS Express which doesn't allow remote connections. It can be configured to allow remote connections, but then you would have to execute Visual Studio as administrator. A better solution is installing IIS and configuring it to behave as reverse proxy. This can be done in Windows 10 Pro by installing URL rewrite and ARR , and configuring it :

  1. First install IIS, go to control panel, Turn Windows Features On or Off, Enable Internet Information Services.
  2. Install URL Rewrite 2.0 from here
  3. Install Application Request Routing 3.0 from here
  4. Open Internet Information Services Manager
  5. Add Web Site. Set site name and physical path. On the bindings section, specify 26308 port (my personal convention: IIS Express port - 1). Leave host name blank.
  6. Click on the newly created web site. On the right pane open "URL Rewrite"
  7. On the Actions pane click on "Add Rule", Select "Reverse Proxy"
  8. Write localhost:26309 on the text box "Enter the server name or the IP address..."
  9. Click OK
  10. Add an exception rule for TCP port 26308 to the Windows Firewall.

Now you need to modify you cordova app to make requests to the newly created web site on IIS. It needs to make requests to http://192.168.8.162:26308 or http://yourMachine.yourDomain.com:26308

In this way you can debug your cordova app and the web api app at the same time, I mean you can add break points to both. It works for emulated devices as well as physical devices attached to USB. You will need a proper wifi accessible by your development machine and device.

2020 UPDATE . What worked for me:

ionic cordova run android --no-native-run --livereload --external

Also adding this to config.xml

<platform name="android">
        <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
...
</platform>

2022 Issue : have been also having the same issue and found out that was using ionic cordova run android -livereload and when i normally run my app it was giving me this error:

net::ERR_CONNECTION_REFUSED when i checked my config i find that -livereload Flag added src="http://localhost:8100" to this

<content original-src="index.html" src="http://localhost:8100" />

instead of this :

<content src="index.html" />

This error can happen due to couple of reasons.

Ensure that the URL you are trying to access is valid or not.

Then make sure you have CORS enabled in your backend application. To do this, use Microsoft.AspNet.WebApi.Cors or if you are using OWIN then in startup.cs configuration, use app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll) (this comes from Microsoft.Owin.Cors )

After you are done doing this, please go to your web.config and type in the following things:

<system.webServer>
 <httpProtocol>
      <customHeaders>
        <clear/>
        <add name="Access-Control-Allow-Credentials" value="true"/>
      </customHeaders>
    </httpProtocol>
</system.webServer>

This will solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM