在React-native和ASP.Net核心RestfulAPI之间进行通信

时间:2020-09-01 10:57:01

标签: react-native

我在使本机应用程序与宁静的api后端通信时遇到问题。

这是后端控制器

[ApiController]
[Route("[controller]")]
public class AuditController : ControllerBase
{
    [HttpGet]
    public IActionResult Audits()
    {
        var audit = new List<AuditRequest>
        {
           new AuditRequest
           {
               Date = "23/04/2019 16:49:37",
               User ="Fiona",
               Message="Logon"
           },
           new AuditRequest
           {
               Date = "23/04/2019 16:49:37",
               User ="Fiona",
               Message="Logon"
           },
           new AuditRequest
           {
               Date = "23/04/2019 16:49:37",
               User ="Fiona",
               Message="Logon"
           }
        };
        return Ok(audit);
    }
}

启动文件

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddCors(opt =>
        {
            opt.AddPolicy("CorsPolicy", policy =>
            {
                policy.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
                //.WithOrigins("http://localhost:3000");
            });
        });
    }

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

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");

        app.UseAuthorization();

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

和我的反应文件。

useEffect(() => {
    axios
      .get("https://localhost:44354/audit")
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
        console.log("error");
      });
    //auditsActions.fetchAudits();
  }, []); 

我可以使用Postman测试终点。

我得到的错误是网络错误

    中的
  • node_modules \ axios \ lib \ core \ createError.js:15:0 dispatchXhrRequest中的
  • node_modules \ axios \ lib \ adapters \ xhr.js:88:12
  • ... 9个来自框架内部的堆栈框架。

我正在使用expo和一个模拟器 enter image description here

有人可以告诉我如何解决此问题吗?

1 个答案:

答案 0 :(得分:0)

最后,我使用了此应用程序-keyoti的传送带。