【发布时间】:2020-05-05 15:43:04
【问题描述】:
我尝试使用 angular 发送 post 请求,但是当我将 content-type 设置为 application/json 始终未设置请求内容类型,始终删除 HTTP 方法,并从请求正文中删除所有发布的数据 这是我的代码
这是我的要求
【问题讨论】:
标签: angular asp.net-core angular8 angular-httpclient angular-http
我尝试使用 angular 发送 post 请求,但是当我将 content-type 设置为 application/json 始终未设置请求内容类型,始终删除 HTTP 方法,并从请求正文中删除所有发布的数据 这是我的代码
这是我的要求
【问题讨论】:
标签: angular asp.net-core angular8 angular-httpclient angular-http
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);
}
}
测试结果
【讨论】:
我只是想扩展飞寒的答案。如果您使用asp core 作为服务器端,您应该在 Startup.cs 中配置 Cors,如下所示:
app.UseCors(x =>
x.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin());
【讨论】:
如果您像这样设置 Accept 标头,就足够了。
const headers = new HttpHeaders()
.set('Accept', 'application/json');
无需设置内容标题。
【讨论】: