简体   繁体   中英

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

I try to send post request with angular but when i set content-type to application/json the request content-type always not set and the HTTP method always removed and all posted data removed from request body here my code

在此处输入图像描述

and here my request

在此处输入图像描述

the HTTP method always removed and all posted data removed from request body

In the screenshot you shared, we can find that the request you captured is a OPTIONS request ( preflight request ), not actual POST request. So the data you posted is not in request body.

Besides, the following code snippet works well on my side, you can refer to it.

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 and Action

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

Test Result

在此处输入图像描述

I just wanted to expand Fei Han answer. If you are using asp core as server side you should configure Cors in Startup.cs like this:

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

If you set Accept headers like this, its enough.

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

No need to set content headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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