Home > front end >  How to debug 422 (Unprocessable Entity) Error Response in Vue/Laravel?
How to debug 422 (Unprocessable Entity) Error Response in Vue/Laravel?

Time:10-01

I am trying to build a simple contact form with Vue 3 and Laravel 8 but am struggling connecting the frontend with the backend. Right now my code produces a 422 (Unprocessable Entity) response but I don't know why and how to investigate. The response occurs indipendent of the passed data values. For example name = null and name = myname produce the same error.

contact.vue:

<template>
  <section class="contact">
    <form @submit.prevent="storeContact" method="post">
      <input type="text" placeholder="Name" v-model="user.name">
      <input type="text" placeholder="Email" v-model="user.email">
      <input type="text" placeholder="Message" v-model="user.message">
      <button action="post" type="submit">Submit</button>
    </form>
  </section>
</template>


<script>
import {ref} from "vue";

export default {
  setup() {
    let success = false;
    let error = false;
    let user = ref({
      name: null,
      email: null,
      message: null
    });
    function storeContact() {
      axios.post('/contact', Object.values(user.value)
      )
        .then((res) => {
          success = true;
        })
        .catch((error) => {
          error = true;
        })
    };
    return {
      success,
      error,
      user,
      storeContact
    }
  }
}
</script>

web.php:

<?php

use Illuminate\Support\Facades\Route;


Route::get('/', function () {
    return view('welcome');
});

Route::post('/contact', 'App\Http\Controllers\ContactController@submit');

ContactController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
  public function submit(Request $request) {
    $this->validate($request, [
      'name' => 'required',
      'email' => 'required | email',
      'message' => 'required'
    ]);
    return response()->json(null, 200);
  }
}

Browser console error:

app.js:17263 POST http://localhost:3000/contact 422 (Unprocessable Entity)

Laravel log has no entry. Does this mean it is a frontend problem?

Edit:

The response in the dev tools network tab shows:

{"message":"The given data was invalid.","errors":{"name":["The name field is required."],"email":["The email field is required."],"message":["The message field is required."]}}

Changing these parameters to text/values brings no change.

CodePudding user response:

As @Mohammed Naguib mentioned, 422 is returned when the validation fails. Based on your validation code - all the properties are required.

$this->validate($request, [
  'name' => 'required',
  'email' => 'required | email',
  'message' => 'required'
]);

So I'll suggest to divide the debugging process into 2.

(1) - Does the front-end sends the data?

on contact.vue, prior to sending the post request. use console.debug to the user object and check the data you send.

   let user = ref({
      name: null,
      email: null,
      message: null
    });
    function storeContact() {
      console.debug(user);
      console.debug(Object.values(user.value));

      axios.post('/contact', Object.values(user.value)

Check the console on the developers tools and check what is the output of the console.debug command for the user object and for the values you send on the request.

If one of the properties is null - something is wrong with the front end.

(2) - Backend

Remove the $this->validate() function and simply var_dump the $request object. Do you see the relevant properties (name, email, address) and do they have the desired values?

My guess:

if i'm not mistaken Object.values(user.value) creates an array with the values so the properties names would be missing from the request.

CodePudding user response:

You're having this issue because you are posting without the CSRF token to the server. Here is a similar case on how to resolve this issue.

How to pass laravel CSRF token value to vue

You will need to copy the CSRF token from the DOM to the header of your axios request or append it to the common headers. Once done, your POST request will be processable. Alternatively to confirm this, you can go to the file app/Http/Middleware/VerifyCsrfToken.php and add your path to the 'except' array

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/contact'
    ];
}

Happy Coding!

  • Related