[ERR_CONNECTION_REFUSED通过使用ReactJS && ASP.NET来获取数据

问题描述 投票:0回答:1

[您好,我正在参加一个班级小组项目,我负责前端部分。我是前端的新秀,所以我可能犯了愚蠢的错误。在我从伙伴那里获得后端代码后:

[ApiController]
    public class AccountController : ControllerBase
    {
        public IDBManager_Users _usersManager;

        public AccountController(IDBManager_Users usersManager)
        {
            _usersManager = usersManager;
        }
        [HttpPost]
        [Route("Account/Create")]
        public bool CreateUser(User user)
        {
            bool created = _usersManager.CreateUser(user);

            return created;
        }

并且我在React中提出了一个获取数据的请求来创建用户:

    register= e => {
        e.preventDefault();
        fetch(`http://localhost:5001/Account/Create`, {
            method: "post",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: this.state.email,
                password: this.state.password,
                userRole: this.state.userRole,
                country: this.state.country,
                place: this.state.place,
                city: this.state.city
            })
        })
            .then((response) => {
                if(response){
                    this.props.history.push('/login')
                }
                else{
                    alert('Please Register with Correct Info!');
                }
            })
            .catch(err => console.log(err));
    };

[我认为所有其他部分都运行良好,可以从Chrome获取请求的有效负载,例如:{"email":"[email protected]","password":"abc","userRole":"1","country":"United States","place":"NY","city":"whatever"}但失败:POST http://localhost:5001/Account/Create net::ERR_CONNECTION_REFUSED我不知道自己做了什么样的愚蠢,但我真的很努力。等待响应:)Edit1:如果您想看看startup.cs,请在此处附加:

    {
        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.Add(new ServiceDescriptor(typeof(SqlManager), new SqlManager(Configuration.GetConnectionString("DefaultConnection"))));

            services.AddControllersWithViews();
             services.AddCors(options =>
    {
          options.AddPolicy("AllowAllHeaders",
                builder =>
            {
                    builder.AllowAnyOrigin()
                           .AllowAnyHeader()
                           .AllowAnyMethod();
                });
    });
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });
            app.UseCors("AllowAllHeaders");
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
asp.net reactjs
1个回答
0
投票

您需要更改方法签名,以使用FromBody批注将JSON从请求主体映射到实际DTO对象:

public bool CreateUser([FromBody] User user)

[请注意,由于您没有从Startup.cs中提供代码,所以我不知道在路由和授权方面是否还有其他遗漏。

参考:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#frombody-attribute

© www.soinside.com 2019 - 2024. All rights reserved.