【问题标题】:Post method fail with Vue.js "500 (Internal Server Error)"Post 方法因 Vue.js “500(内部服务器错误)”而失败
【发布时间】:2017-10-05 14:53:12
【问题描述】:

所以我试图将数据存储在我的election_users 表中,但发出 POST 请求会出现“500(内部服务器错误)”错误。我的对象确实返回了正确的“election_id”。我不知道我做错了什么。

这是我的 vue 脚本中的方法:

methods: {
      createVote: function () {
        var itemId = this.$route.params.id
        var input = this.newUserVoted
        this.newUserVoted.election_id = itemId
        this.$http.post('http://www.nmdad2-05-elector.local/api/v1/electionuser', input)
          .then((response) => {
            this.newUserVoted = {'election_id': itemId}
          }).catch(e => {
            console.log(e)
            console.log(input)
          })
      }
    },

我的 UsersController.php

public function store(Request $request)
    {

        $userVoted = new ElectionUser();
        $userVoted->election_id = $request['election_id'];
        $userVoted->user_id = Auth::id();

        if ($userVoted->save()) {


            return response()
                ->json($userVoted);

        }

    }

我的路由Api.php

   Route::post( 'electionuser', 'UsersController@store' );

我的 ElectionUser.php

class ElectionUser extends Model
{
    // Relationships
    // =============

    protected $fillable = [
        'election_id',
        'user_id'
    ];

    public function election()
    {
        return $this->belongsToMany(Election::class);
    }

}

【问题讨论】:

标签: php laravel vue.js


【解决方案1】:

您需要添加 CSRF 令牌: https://laravel.com/docs/5.4/helpers#method-csrf-token

例如在视图中

<script>
  var csrf = '{{csrf_token()}}';
</script>

在你的脚本中

var formData = new FormData();

formData.append('_token', csrf);
formData.append('input', this.newUserVoted);

this.$http.post('http://www.nmdad2-05-elector.local/api/v1/electionuser', formData)

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2019-06-26
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多