簡體   English   中英

React Native 應用程序沒有響應我的本地 .net api

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

伙計們,我剛開始使用 react native,我已經嘗試了很多使它與 .net api 一起工作的東西,但是當它變成通過模擬器發送獲取請求時,它顯示“網絡請求失敗”。 我用谷歌搜索了所有內容,但沒有解決方案,只能獲取“10.0.2.2”而不是我的本地 IP。 我做錯了什么或者我錯過了什么?

應用程序.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;

啟動設置.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"
      }
    }
  }
}

啟動.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();
        });
    }

程序.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>();
            });

數據庫上下文.cs

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

用戶.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; }

}

我必須對 .Net api 進行更改,它可以工作

在 startup.cs 上評論這一行

        //app.UseHttpsRedirection();

啟動設置.json

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

將此行更改為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM