AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79064136
Accepted
Isaac Cortés
Isaac Cortés
Asked: 2024-10-08 10:23:10 +0800 CST2024-10-08 10:23:10 +0800 CST 2024-10-08 10:23:10 +0800 CST

如何解决 PUT 422(无法处理的内容)错误

  • 772

我正在做一个简单的大学项目,一个电影目录,但我遇到了一个无法找到解决方案的问题。当尝试更新电影时,我收到 422 错误,我无法找出问题所在。我使用 Laravel 10 创建了我的 API,我与您分享我的控制器,特别是更新方法,因为这是我收到错误的地方,以及我的路线:

影片控制器.php

  public function updateMovie(Request $request, $id)
    {
        Log::info('Request data:', $request->all());
        Log::info('Request files:', $request->file());
    
        if (!$request->has('title')) {
            Log::error('Title is missing');
        }
        if (!$request->has('synopsis')) {
            Log::error('Synopsis is missing');
        }
        if (!$request->has('year')) {
            Log::error('Year is missing');
        }
    
        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'synopsis' => 'required|string',
            'year' => 'required|integer|min:1900|max:' . date('Y'),
            'cover' => 'nullable|file|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

api.php

Route::put('/movies/{id}', [MovieController::class, 'updateMovie']);

我认为问题不在于我的 API,而在于我的客户端。我使用 Angular 16 作为前端。现在,我将向您展示我的编辑组件和我服务的配置:

电影.编辑.组件.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MovieService } from '../../services/movie.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-movie-edit',
  templateUrl: './movie-edit.component.html',
  styleUrls: ['./movie-edit.component.scss']
})
export class MovieEditComponent implements OnInit {
  movieForm: FormGroup;
  movieId!: number;
  movie: any;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private movieService: MovieService,
    private fb: FormBuilder
  ) {
    this.movieForm = this.fb.group({
      title: ['', Validators.required],
      synopsis: ['', Validators.required],
      year: ['', [Validators.required, Validators.min(1900), Validators.max(new Date().getFullYear())]],
      cover: [null]
    });
  }

  ngOnInit(): void {
    this.movieId = Number(this.route.snapshot.paramMap.get('id'));
    this.getMovieDetails();
  }

  getMovieDetails(): void {
    this.movieService.getMovieById(this.movieId).subscribe({
      next: (data) => {
        this.movie = data;
        this.movieForm.patchValue({
          title: this.movie.title,
          synopsis: this.movie.synopsis,
          year: this.movie.year
        });
      },
      error: (error) => {
        console.error('Error fetching movie details', error);
      }
    });
  }

  onFileChange(event: any): void {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.movieForm.patchValue({
        cover: file
      });
    }
  }

  onSubmit(): void {
    if (this.movieForm.valid) {
      const formData = new FormData();
      const title = this.movieForm.get('title')?.value || '';
      const synopsis = this.movieForm.get('synopsis')?.value || '';
      const year = this.movieForm.get('year')?.value;
      const cover = this.movieForm.get('cover')?.value;
  
      console.log('Title:', title);
      console.log('Synopsis:', synopsis);
      console.log('Year:', year);
      console.log('Cover:', cover);
  
      formData.append('title', title);
      formData.append('synopsis', synopsis);
      if (year !== undefined && year !== null) {
        formData.append('year', year.toString());
      }
      if (cover) {
        formData.append('cover', cover);
      }
  
      formData.forEach((value, key) => {
        console.log(key, value);
      });
  
      this.movieService.updateMovie(this.movieId, formData).subscribe({
        next: () => {
          this.router.navigate(['/movie', this.movieId]);
        },
        error: (error) => {
          console.error('Error updating movie', error);
        }
      });
    }
  }
}

电影.服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MovieService {
  private apiUrl = 'http://localhost:8000/api/movies';

  constructor(private http: HttpClient) {}

  getAllMovies(): Observable<any> {
    return this.http.get(this.apiUrl);
  }

  getMovieById(id: number): Observable<any> {
    return this.http.get(`${this.apiUrl}/${id}`);
  }

  createMovie(movie: any): Observable<any> {
    const formData = new FormData();
    formData.append('title', movie.title);
    formData.append('synopsis', movie.synopsis);
    formData.append('year', movie.year.toString());
    formData.append('cover', movie.cover);

    return this.http.post(this.apiUrl, formData);
  }

  updateMovie(id: number, formData: FormData): Observable<any> {
    return this.http.put(`${this.apiUrl}/${id}`, formData);
  }

  deleteMovie(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/${id}`);
  }
}

看起来数据没有到达后端;FormData 从 Angular 发送的方式似乎存在问题。

这是日志文件中显示的内容:

[2024-10-08 00:33:17] local.INFO: Request data:  
[2024-10-08 00:33:17] local.INFO: Request files:  
[2024-10-08 00:33:17] local.ERROR: Title is missing  
[2024-10-08 00:33:17] local.ERROR: Synopsis is missing  
[2024-10-08 00:33:17] local.ERROR: Year is missing  

请帮忙,我需要在两周内提交这项活动。

angular
  • 3 3 个回答
  • 42 Views

3 个回答

  • Voted
  1. Best Answer
    hungbad
    2024-10-08T11:01:20+08:002024-10-08T11:01:20+08:00

    您可以尝试POST使用带有参数的方法_method="PUT",因为提交时 PHP 无法multipar-form-data正确识别使用该PUT方法上传文件。

    因此,将您的提交表单方法更改为POST并添加

    formData.append('_method', 'PUT');
    
    • 1
  2. IGP
    2024-10-08T10:30:27+08:002024-10-08T10:30:27+08:00

    由于您正在使用FormData,我认为您需要Content-Type为POST和PUT请求设置标题。

    createMovie(movie: any): Observable<any> {
        ...
        const options = {
            headers: new HttpHeaders({ "Content-Type": "multipart/form-data" }),
        };
    
        return this.http.post(this.apiUrl, formData, options);
    }
    
    updateMovie(id: number, formData: FormData): Observable<any> {
        const options = {
            headers: new HttpHeaders({ "Content-Type": "multipart/form-data" }),
        };
    
        return this.http.put(`${this.apiUrl}/${id}`, formData, options);
    }
    

    为了将来进行调试,您可以将变量输出到日志文件中。

    Log::debug($request->all());
    
    • 0
  3. Jijesh Cherayi
    2024-10-08T11:07:27+08:002024-10-08T11:07:27+08:00

    请使用 Json 数据从 angular 提交数据,而不是 formData... { "year": document.getElementByID(" year"), .... .... } 像这样

    • -1

相关问题

  • 日期管道不适用于设置了 FormControlName 属性的元素

  • 我可以根据上述场景将可重用组件的服务放置在 Angular 的核心模块中吗

  • mat-dialog-close 数据绑定为 True 后,Mat 对话框不会关闭

  • 无法在 app.component.html 中呈现自定义组件

  • 在超过 2 个 .ts 文件中重用 component.html

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve