【问题标题】:angular post request with content-type application/json not working内容类型应用程序/json的角度发布请求不起作用
【发布时间】:2020-05-05 15:43:04
【问题描述】:

我尝试使用 angular 发送 post 请求,但是当我将 content-type 设置为 application/json 始终未设置请求内容类型,始终删除 HTTP 方法,并从请求正文中删除所有发布的数据 这是我的代码

这是我的要求

【问题讨论】:

    标签: angular asp.net-core angular8 angular-httpclient angular-http


    【解决方案1】:

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

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

    另外,下面的代码sn-p在我这边效果很好,大家可以参考一下。

    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);
    });
    

    控制器和动作

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

    测试结果

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

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

        无需设置内容标题。

        【讨论】:

        • 在这种情况下,数据发布到服务器,但内容类型将是纯文本,此请求将给我异常不受支持的媒体类型
        猜你喜欢
        • 1970-01-01
        • 2018-09-03
        • 2017-10-29
        • 2016-12-24
        • 1970-01-01
        • 2017-01-28
        • 2012-11-30
        • 1970-01-01
        • 2020-05-31
        相关资源
        最近更新 更多