【问题标题】:POST http://localhost:8000/api/projects/ 500 (Internal Server Error)POST http://localhost:8000/api/projects/ 500(内部服务器错误)
【发布时间】:2021-09-07 00:28:09
【问题描述】:

我正在开发一个 rest api 项目,我正在使用 Laravel 和 Angular。恢复,我的项目就像一个项目经理。我有 4 个表:用户、项目、项目用户和状态。 所以当用户创建一个项目时,他只写名字就创建了项目。 creator_id 是当前用户 ID。对于后端,我使用 Laravel JWT 进行身份验证。这是控制器创建项目的代码:

项目模型:

class Project extends Model
{
    protected $fillable = [
        'name',  'creator_id', 'status_id'
    ];

    protected $hidden = [
        'created_at', 'updated_at'
    ];

    protected $table = 'projects';

    public function users()
    {
        return $this->belongsToMany(User::class)->select( 'email', 'date_of_birth', 'firstname', 'lastname');
    }

    public function status()
    {
        return $this->belongsTo(Status::class);
    }
}

所以后端的路线有效,我尝试使用 Postman,一切都很好。但是我在前端创建项目时遇到了问题。它不起作用,我收到错误 500(内部服务器错误)。当我检查网页时,出于安全考虑,我收到了以下消息:

这是我的角码:

export class AddProjectComponent implements OnInit {

  project = {
    name: '',
  };

  submitted = false;
  constructor(private projectService: ProjectService) { }

  ngOnInit() {
  }

  createProject(): void {
    const data = {
      name: this.project.name,
    };
    this.projectService.create(data)
      .subscribe(
        response => {
          console.log(response);
          this.submitted = true;
        },
        error => {
          console.log(error);
        }
      );
  }

  newProject(): void {
    this.submitted = false;
    this.project = {
      name: ''
    };
  }
}

project.service.ts

  create(data): Observable<any>{
    return this.http.post(`http://localhost:8000/api/projects/`, data);
  }

我不知道为什么它不起作用,因为我的用户连接良好,我在本地存储中有他的 auth_token。

有人可以帮助我吗? ^^

我认为我已经放置了最有用的文件,但如果它们丢失了,我可以将它们添加给你。

提前致谢

【问题讨论】:

  • 你是否在模型中设置了时间戳为假?
  • @JohnLobo 不,我没有
  • 添加有问题的型号代码
  • 尝试一次这个 $request->merge(['creator_id'=>Auth::id()]) 而不是添加
  • @JohnLobo 它适用于合并!太感谢了 ! ;)

标签: php angular laravel typescript jwt


【解决方案1】:

问题在于$request-request-&gt;add(['creator_id'=&gt;Auth::id()])

而不是使用request merge

$request->merge(['creator_id'=>Auth::id()]) 

【讨论】:

    【解决方案2】:

    您的答案就在错误消息中。 creator_id 没有默认值,这意味着您必须将值传递给它才能在数据库中创建行

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 2022-10-04
      • 2023-02-20
      • 2016-07-29
      • 2017-08-17
      • 1970-01-01
      • 2019-12-22
      • 2012-03-16
      相关资源
      最近更新 更多