React Native:调用在本地主机上运行的 API

23k*_*23k 3 .net rest .net-core react-native expo

我有一个在我的机器上本地运行的 API。我试图在开发环境中访问这些数据并遇到问题。

当我通过 expo 运行我的 React Native 应用程序时,localhost是指设备本地主机,而不是在我的桌面上运行的设备。我对此进行了大量研究,最重要的建议是查询您的内部 IP 地址而不是localhost.

当我查询时,localhost我抛出一个没有详细信息的异常:

Network request failed

当我查询我的内部 IP 时,请求挂起,没有任何反应。

我通过这个命令开始博览会: expo start --tunnel

这是发出请求的代码:

fetch("http://localhost:5001/api/standings")
    .then((res) => console.log(res))
    .catch((err) => console.log(err))
Run Code Online (Sandbox Code Playgroud)

.NETAPI的工作原理,通过镀铬。在localhost我和我的内部 IP 上(带有关于不安全连接的警告)。

我缺少任何其他配置吗?

编辑:

这是邮递员的回复:

邮差

这是我的 Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddHttpClient();
        services.AddCors();
        services.AddEnv((builder) =>
        {
            builder
            .AddEnvFile(".env")
            .AddThrowOnError(true)
            .AddEncoding(Encoding.ASCII);
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseCors(builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
        });

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*rdo 6

您是否尝试过使用ngrok来公开您的 API?

在我的团队中,当我们想要测试我们在 localhost 中运行的 API 版本,同时也在我们的模拟器中运行移动应用程序时,我所做的工作是使用 ngrok 公开 API 的本地版本并将我们的应用程序指向ngrok 的网址。

ngrok 通过安全隧道将 NAT 和防火墙后面的本地服务器暴露给公共互联网。

这是一个指南,应该有助于在 Windows 机器上启动和运行 ngrok。