为啥在尝试使用 Angular 检索数据库信息时出现错误 415?

Posted

技术标签:

【中文标题】为啥在尝试使用 Angular 检索数据库信息时出现错误 415?【英文标题】:Why am i getting error 415 when trying to retrieve database information wiht angular?为什么在尝试使用 Angular 检索数据库信息时出现错误 415? 【发布时间】:2021-03-01 16:54:02 【问题描述】:

我现在正在学习 Angular,我正在尝试将 POST 放入 asp.net 核心中的 API。 我去了初创公司并制作了cors,因为他们给我带来了问题。现在,我的问题是错误 415,我不知道为什么说不支持有效负载,这对我来说是 0 意义。 我的 API 函数是这样的:

 [HttpPost]
        public IActionResult register([FromBody] RegisterModel registro)
        
            Cristais cristal = new Cristais  ID = "4", Cristal = "Zombie44" ;
            _context.Cristais.Add(cristal);
            _context.SaveChanges();
            Utilizadores utilizador = new Utilizadores();
            utilizador.ID = Guid.NewGuid().ToString();
            utilizador.Comida = 100;
            utilizador.Gold = 1000;
            utilizador.ID_Cristal = "4";
            utilizador.Email = registro.email;
            utilizador.NickName = registro.nickName;
            utilizador.Password = registro.password;
            _context.Utilizadores.Add(utilizador);
            _context.SaveChanges();
            Console.WriteLine(_context.Utilizadores.Where(p=> p.ID_Cristal=="4"));
            return Ok(_context.Utilizadores.ToList());
        

然后我在 Angular 中尝试了我的帖子:

registar() 
    console.log(this.utilizador);
    console.log(config.Urlsite);
    this.httpClient.post(config.Urlsite + "Utilizador/register",this.utilizador, headers: new HttpHeaders('Content-Type': 'json') ).subscribe((resultado)=>
        console.log(resultado);
    , (casoErro)=>
        console.log(casoErro);
    )
  

utilizador 是一个以 json 形式包含用户信息的变量,例如:

"nickName": "Ricardo", "password": "Zombie33", "email": "aasd@hotmail.com"

另外,API 函数中的 registro 是一个有 3 个字符串的模型...

如果我在邮递员中尝试这个,一切都会顺利。我不明白为什么我不能用角度来做 感谢所有帮助,谢谢! :)

[编辑] 我只是试图放置 [EnableCors("StratGameWebSiteAngular")] 在 API 函数上,然后我得到了错误 500.. 我现在迷路了

【问题讨论】:

【参考方案1】:

我的问题是错误 415,我不知道为什么说不支持有效负载

在您的 Angular 客户端代码中,我们可以发现您设置了 headers: new HttpHeaders('Content-Type': 'json'),这导致了问题。

您可以将Content-Type 设置为application/json,如下所示。

this.httpClient
  .post(
    config.Urlsite + "Utilizador/register",
    this.utilizador,
     headers: new HttpHeaders( "Content-Type": "application/json" ) 
  )
  .subscribe(
    resultado => 
      console.log(resultado);
    ,
    casoErro => 
      console.log(casoErro);
    
  );

测试结果

【讨论】:

以上是关于为啥在尝试使用 Angular 检索数据库信息时出现错误 415?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在尝试将 Angular 父组件的属性绑定到子组件时出现此错误?

为啥在 Vue js 中尝试从 firebase 检索令牌时出现错误?

Angular 2:为啥在检索路由参数时使用 switchMap?

为啥调用 API 时出现 CORS 错误

尝试获取数据库信息时出现问题(mysql)

为啥这个 Angular 脚本无法检索 Laravel 4 生成的 JSON?