简体   繁体   中英

React Native app doesn't response my local .net api

Guys i'm just getting started to work with react native and i've tried lots of things that make it work with .net api but when it becomes to send a get request through emulator, it says "Network request failed". I googled it all in deep but there is no solution but fetch to "10.0.2.2" instead of my local ip. What did i do wrong or what did i missed?

app.js

async function getAll() {
  console.warn('getAll');
  return fetch('https://10.0.2.2:5001/api/Users/getall')
    .then(response => response.json().data)
    .then(response => console.log(response))
    .catch(error => console.error(error));
}

const App: () => Node = () => {
  const [users, setUsers] = useState(getAll());

  return (
    <View style={styles.menu}>
      <SectionList
        sections={[{title: 'Users', data: users}]}
        renderItem={({item}) => (
          <Text style={styles.user}>{item.userName}</Text>
        )}
        renderSectionHeader={({section}) => (
          <Text style={styles.header}>{section.title}</Text>
        )}
        keyExtractor={(item, index) => index}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
  user: {
    fontSize: 16,
    marginTop: 12,
    color: '#1e90ff',
  },
  header: {
    fontSize: 24,
    marginBottom: 16,
    color: '#00bfff',
  },
  menu: {
    backgroundColor: '#006400',
  },
});

export default App;

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:45028",
      "sslPort": 44367
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

startup.cs

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();
        services.AddCors();
        services.AddHttpContextAccessor();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
        });

        services.AddDependencyResolvers(new ICoreModule[] {
            new CoreModule()
        });
    }

    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
        }

        app.UseHttpsRedirection();

        app.UseWebSockets();

        app.UseRouting();

        app.UseAuthentication();

        app.UseStaticFiles();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureContainer<ContainerBuilder>(builder =>
            {
                builder.RegisterModule(new AutofacBusinessModule());
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

databaseContext.cs

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=localhost\SQLEXPRESS;Database=Mobile;Trusted_Connection=True");
    }

user.cs

public class User : IEntity
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Gender { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }

}

I have to make changes on .Net api and it works

comment this line on startup.cs

        //app.UseHttpsRedirection();

launchsettings.json

"applicationUrl": "https://localhost:5001", "http://localhost:5000",

change this line to

"applicationUrl": "http://localhost:5000",

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