简体   繁体   中英

What causes the "419 unknown status" error in this Laravel 8 application?

I am making a blogging application with Laravel 8 and Bootstrap 5. It has a user profile management system.

I want to enable every user to add and delete her/his avatar . For this purpose, I have a deleteavatar() method in my UserController controller:

public function deleteavatar($id, $fileName)
{
  $current_user = Auth::user();
  $current_user->avatar = "default.png";
  $current_user->save();

  if (File::exists(public_path('images/avatars/' . $fileName))) {
    File::delete(public_path('images/avatars/' . $fileName));
  }
}

In the routes file:

Route::group(['prefix' => 'user'], function() {
    Route::get('/', [UserController::class, 'index'])->name('user');
    Route::match(['get', 'post'],'/update', [UserController::class, 'update'])->name('user.update');
    Route::post('/deleteavatar/{id}/{fileName}', [UserController::class, 'deleteavatar'])->name('user.deleteavatar');
});

I use this piece of JavaScript to call the above method:

function deleteAvatar(e) {
    e.preventDefault();

    var avatar = document.querySelector('#avatar-container img');
    var topAvatar = document.querySelector('#top_avatar');
    var trashIcon = e.currentTarget;
    var defaultAvatar = APP_URL + '/images/avatars/default.png';

    //Get user's ID
    var id = trashIcon.dataset.uid;
    var fileName = avatar.getAttribute('src').split('/').reverse()[0];

    var url = APP_URL + `/dashboard/user/deleteavatar/${id}/${fileName}`;

    if (confirm('Delete the avatar?')) {
      var CSRF_TOKEN = document.querySelectorAll('meta[name="csrf-token"]')[0].getAttribute('content');

      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
          if (xmlhttp.status == 200) {
              avatar.setAttribute('src', defaultAvatar);
              topAvatar.setAttribute('src', defaultAvatar);
              trashIcon.remove();
          }
        }
      }

      xmlhttp.open('POST', url, true);
      xmlhttp.send();
    }
}
document.querySelector('#delete-avatar').addEventListener('click', deleteAvatar);

The problem

For a reason I have been unable to find out, the Chrome console throws this 419 (unknown status) .

What is my mistake?

Laravel is returning http status 419 because of missing csrf token. Add the csrf token in a HTML meta tag and add to your ajax request header as well.

For reference: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token

set xmlhttp header for csrf token

function deleteAvatar(e) {
    e.preventDefault();

    var avatar = document.querySelector('#avatar-container img');
    var topAvatar = document.querySelector('#top_avatar');
    var trashIcon = e.currentTarget;
    var defaultAvatar = APP_URL + '/images/avatars/default.png';

    //Get user's ID
    var id = trashIcon.dataset.uid;
    var fileName = avatar.getAttribute('src').split('/').reverse()[0];

    var url = APP_URL + `/dashboard/user/deleteavatar/${id}/${fileName}`;

    if (confirm('Delete the avatar?')) {
        var CSRF_TOKEN = document.querySelectorAll('meta[name="csrf-token"]')[0].getAttribute('content');

        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
                if (xmlhttp.status == 200) {
                        avatar.setAttribute('src', defaultAvatar);
                        topAvatar.setAttribute('src', defaultAvatar);
                        trashIcon.remove();
                }
            }
        }

        xmlhttp.open('POST', url, true);
        xmlhttp.setRequestHeader("X-CSRF-TOKEN", CSRF_TOKEN);
        xmlhttp.send();
    }
}
document.querySelector('#delete-avatar').addEventListener('click', deleteAvatar);

Ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Ref: https://laravel.com/docs/9.x/csrf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM