Reputation: 1399
I have an API that I'm running locally on my machine. I'm trying to access this data in a development environment and running into issues.
When I have my React Native app running through expo, localhost
is referring to the devices localhost and not the one running on my desktop. I have researched this quite a bit and the top suggestion is to query your internal IP address instead of localhost
.
When I query localhost
I get an exception thrown with no details:
Network request failed
When I query my internal IP, the request hangs and nothing happens.
I'm starting expo through this command: expo start --tunnel
Here is the code making the request:
fetch("http://localhost:5001/api/standings")
.then((res) => console.log(res))
.catch((err) => console.log(err))
The .NET
API works through chrome. On both localhost
and my internal IP (with a warning about an unsecure connection).
I there any additional configuration I'm missing?
EDIT:
Here is the Postman response:
Here is my 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();
}
}
Upvotes: 5
Views: 3999
Reputation: 1393
Have you tried using ngrok to expose your API?
In the team I work on what we do when we want to test our version of the API running in the localhost, while also running the mobile app in our simulators, is to expose the local version of the API with ngrok and point our app to ngrok's URL.
ngrok exposes local servers behind NATs and firewalls to the public internet over secure tunnels.
Here's a guide that should help with getting ngrok up and running in a Windows machine.
Upvotes: 11
Reputation: 586
It looks like a cross-origin issue. You can't send a request to another domain. Need to enable Cross-Origin Request.
How to do it for asp.net core - https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
How to do it for asp.net webapi - https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Both links have great explanations.
Upvotes: 0