angular - 从 Angular 12 到 Laravel 8 api 的 Multipart/form-data 问题
问题描述
我正在尝试将一些字段数据和文件发送到 Laravel 后端。如果我尝试使用 Postman 使用 api,但当我通过 Angular 发送它时总是显示错误,它是有效的
HttpErrorResponse {headers: HttpHeaders, status: 422, statusText: 'Unprocessable Entity', url: 'http://127.0.0.1:8000/api/works', ok: false, …}
error:
errors:
category: ['The category field is required.']
picture: ['The picture field is required.']
title: ['The title field is required.']
title_en: ['The title en field is required.']
title_uz: ['The title uz field is required.']
[[Prototype]]: Object
message: "The given data was invalid."
[[Prototype]]: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://127.0.0.1:8000/api/works: 422 Unprocessable Entity"
name: "HttpErrorResponse"
ok: false
status: 422
statusText: "Unprocessable Entity"
url: "http://127.0.0.1:8000/api/works"
[[Prototype]]: HttpResponseBase
就像 Laravel 没有看到任何必填字段一样。
角函数:
onSubmit() {
const formData = new FormData()
formData.append('title', this.worksForm.get('title')!.value)
formData.append('title_en', this.worksForm.get('title_en')!.value)
formData.append('title_uz', this.worksForm.get('title_uz')!.value)
formData.append('category', this.worksForm.get('category')!.value)
formData.append('description', this.worksForm.get('description')?.value)
formData.append('description_en', this.worksForm.get('description_en')?.value)
formData.append('description_uz', this.worksForm.get('description_uz')?.value)
formData.append('picture', this.worksForm.get('picture')?.value)
const headers = new HttpHeaders().append('Content-Type', ['multipart/form-data']);
this.http.post(`${environment.apiUrl}works`, formData,
{
headers: headers
}
).subscribe(
(res) => console.log(res),
(err) => console.log(err)
)
}
Laravel 商店()
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'title_en' => 'required',
'title_uz' => 'required',
'category' => 'required',
'picture' => 'required'
]);
if ($file = $request->file('picture')) {
$name = $file->getClientOriginalName();
$path = $request->file('picture')->storeAs('public/pictures', $name);
$request['picture'] = $name;
}
$input = $request->all();
$input['picture'] = $name;
return Work::create($input);
}
我已经在考虑尝试其他后端......还是我前面有错误?
对于此类问题,我在这里没有找到任何可行的答案。
解决方案
推荐阅读
- python - Pandas 有条件地创建大量数据框列
- c++ - 如何用现有的基类指针构造一个类?
- android - 活动在 startActivity(intent) 之后没有启动
- python - Python 2.7 tkinter - 与 widget.tk_focusNext().focus() 相反
- ansible - Ansible:为文件和目录设置 ACL
- android - 有没有一种优雅的方式来保存和恢复 Kotlin 中的视图状态?
- amazon-web-services - 在轮询之前从 AWS SQS 队列中删除一些消息
- gremlin - aws 海王星因大图下降而超时 ()
- c++ - 必需:以字符串模 11 存储的大数(最多 1000 位)
- kernel - 在内核树外编译 ebpf _kern.c 并将独立的 libbpf 链接到 _user.c