我想知道我做错了什么 . 我收到了400个错误的请求,试图通过角度服务发送帖子请求 . 我有2个实体 - Document和DocumentCategory(多对多关系) . 我可以发布文档本身(没有类别)没有问题 .
document-create.component.ts
createDocument(title, body, categories) {
let document = {title: title, body: body, categories: categories};
this._crudService.createDocument(document).subscribe(
data => {
return true;
},
error => {
console.error("Error saving document! " + error);
return Observable.throw(error);
}
);
}
crudService.ts
createDocument(document) {
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
//let body = JSON.stringify(document);
let body = document;
return this.http.post
('http://localhost:8000/documents', body, headers);
}
The form
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class)
->add('body', TextType::class)
//->add('categories', TextType::class)
->add('categories', EntityType::class, array(
'class' => 'AppBundle:DocumentCategory',
'multiple' => true,
'expanded' => true,
'by_reference' => false,
'choice_label' => 'id',
))
;
}
Document.php
/**
* @ORM\ManyToMany(targetEntity="DocumentCategory", mappedBy="documents")
* @JMSSerializer\Expose
*/
private $categories;
DocumentCategory.php
/**
* @ORM\ManyToMany(targetEntity="Document", inversedBy="categories")
* @ORM\JoinTable(name="document_category_document")
* @JMSSerializer\Expose
*/
private $documents;
Request
POST / documents HTTP / 1.1 Accept:application / json,text / plain,/ Accept-Encoding:gzip,deflate,br Accept-Language:en-US,en; q = 0.8 Connection:keep-alive Content-Length:213 Content -Type:application / json主机:localhost:8000来源:http://localhost:4200 Referer:http://localhost:4200/admin/document/create User-Agent:Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 55.0.2883.87 Safari / 537.36 X-Php -Ob-Level:1
{
"title": "t",
"body": "<p>b</p>",
"categories": [
{
"id": 1,
"name": "cat1",
"documents": []
},
{
"id": 2,
"name": "cat2",
"documents": []
}
]
}
正如我所说,如果我删除类别,一切正常 . 我无法弄清楚:(
编辑:当我尝试发送上面的json作为application / json时,Postman显示此响应:
{
"children": {
"title": {},
"body": {},
"categories": {
"errors": [
"This value is not valid."
],
"children": {
"1": {},
"2": {},
"3": {},
"4": {}
}
}
}
}
1 回答
经过一段时间后,我终于成功了 . 这是我的结果,以防有人出现类似问题 . 这不是最优雅的解决方案,我会尝试找到一个更好的解决方案,但至少它是有效的 . 问题出在控制器上 . 现在post方法看起来像这样:
我的表格很简单: