使用 ASP.NET Core 创建 Web API使用 JavaScript 调用报错 webapi Unable to get items. TypeError: Failed to fetch

最近用微软官网文档学习ASP.NET Core 创建 Web API时报错,官网学习链接1官网学习链接2,解决方案如下:

 

1.在StartUp.cs里Configure方法里介于app.UseRouting()和app.UseEndpoints()添加app.UseCors();

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthorization();

app.UseCors();

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

2.在StartUp.cs里ConfigureServices方法里添加services.AddCors();

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.WithOrigins("*")
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
            });

            services.AddControllers();

            services.AddDbContext<TodoContext>(opt =>
                                               opt.UseInMemoryDatabase("TodoList"));

            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "TodoItems", Version = "v1" });
            //});
        }

3.在TodoItemsController.cs添加应用一下默认属性。

 

 参考资料:

https://blog.csdn.net/weixin_30544657/article/details/94884203

https://stackoverflow.com/questions/49343024/getting-typeerror-failed-to-fetch-when-the-request-hasnt-actually-failed

 

posted @ 2021-11-02 15:18  LeeMacrofeng  阅读(281)  评论(0编辑  收藏  举报