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

时间:2019-02-03 05:48:07

标签: .net rest react-native .net-core expo

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

当我的React Native应用通过expo运行时,localhost是指设备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))

.NET API通过chrome运行。在localhost和我的内部IP上(带有关于不安全连接的警告)。

我还有其他配置吗?

编辑:

这是邮递员的回复:

Postman

这是我的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();
    }
}

2 个答案:

答案 0 :(得分:2)

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

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

  

ngrok通过安全隧道将位于NAT和防火墙后面的本地服务器公开到公共Internet。

这里有一个guide,应该有助于在Windows机器上启动ngrok并使其运行。

答案 1 :(得分:0)

这似乎是跨域问题。您无法将请求发送到另一个域。需要启用跨域请求

如何针对 asp.net核心-https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

如何针对 asp.net webapi -https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

两个链接都有很好的解释。