繁体   English   中英

angular 发布请求,内容类型应用程序/json 不起作用

[英]angular post request with content-type application/json not working

我尝试使用 angular 发送发布请求,但是当我将内容类型设置为应用程序/json 时,请求内容类型始终未设置,并且 HTTP 方法总是被删除,并且所有发布的数据都从请求正文中删除我的代码

在此处输入图像描述

这是我的要求

在此处输入图像描述

HTTP 方法总是被删除,所有发布的数据都从请求正文中删除

在您分享的屏幕截图中,我们可以发现您捕获的请求是一个OPTIONS请求( 预检请求),而不是实际的POST请求。 因此,您发布的数据不在请求正文中。

此外,以下代码片段对我来说效果很好,您可以参考它。

var student = {'name' : 'testuser', 'age' : 29};

const headers = new HttpHeaders().set('Content-Type','application/json');

this.http.post<Student>('https://xxxx/student',JSON.stringify(student),{headers:headers})
.subscribe(data => {
  console.log(data);
});

Controller 和动作

[Route("[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
    [HttpPost]
    public IActionResult Post(Student student)
    {
        return Ok(student);
    }
}

测试结果

在此处输入图像描述

我只是想扩大飞寒的答案。 如果您使用asp core作为服务器端,您应该在 Startup.cs 中配置 Cors,如下所示:

app.UseCors(x =>
    x.AllowAnyHeader()
    .AllowAnyMethod()
    .AllowAnyOrigin());

如果您像这样设置 Accept 标头,就足够了。

 const headers = new HttpHeaders()
      .set('Accept', 'application/json');

无需设置内容标题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM