php - Laravel 无法读取表单数据

标签 php angular laravel

我正在制作一个网络应用程序,在前端使用 Angular,在后端使用 Laravel。 但是当我尝试将一些数据上传到 laravel API 时遇到一些问题。

我在 Angular 上使用表单数据,因为我需要它来上传文件。但是当我将数据发送到 Laravel 时,它没有通过验证,因为 Laravel 获取的是空数据。

这是提交时调用的函数。

  onUpload() {
    const fd = new FormData;
    fd.append('video', this.video);
    fd.append('image', this.image);
    fd.append('title', 'Hello world');
    fd.append('description', 'Hello world');
    fd.append('userId', '1');
    fd.append('categoryId', '1');

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post('here goes the real url', fd, {
      headers: headers
    }).subscribe(event => {
        console.log(event);
    });
  }

这是我在 Laravel 上的验证器。

    public function rules(){
        $datos = $this->validationData();
        return [
            "description" => ["max:2000"],
            "video" => ["required", "mimes:mp4,mov,ogg"],
            "image" => ["required", "image", "mimes:jpg,jpeg,png,gif,webp"],
            "title" => ["required","min:4", "max:100"],
            "userId" => ["required", "numeric"],
            "categoryId" =>["numeric"]
        ];
    }

而且,这是错误消息:

errors:
image: ["The image field is required."]
title: ["The title field is required."]
video: ["The video field is required."]
userId: ["The user id field is required."]
__proto__: Object
message: "The given data was invalid."

我需要在 Laravel 上添加一些额外的东西来读取数据?还是我上传错了? 非常感谢您抽出时间。

最佳答案

尝试将Content-type更改为multipart/form-data

const headers = new HttpHeaders({
      'Content-Type': 'multipart/form-data'
});

关于php - Laravel 无法读取表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608520/

相关文章:

php - Laravel Auth::user 在其他 Controller 中找不到

php - 有一个通过 Laravel Eloquent

php - 从第二个表中提取某些信息但没有 "Where"约束

angularjs - 单个数组 JSON 对象不会打印 (Ionic 2)

angular - NGXS:如何测试一个 Action 是否被调度?

angular - 在 Angular 5 中验证后防止提交表单

database - Laravel DB::update 只返回 0 或 1

php - google.maps.InfoWindow

php - FckEditor 转换 nbsp;一些奇怪的人物?

php - 如何以编程方式登录/验证用户?