mutaz's avatar
Level 7

Request failed with status code 422 : AxiosError

I tried to submit the form using axios to avoid refresh the page but it fails with post method

    <form
    action="/books/{{$book->title}}/comments" method="POST"
    >
    @csrf

    <header class="flex items-center">
        <img
        src="https://i.pravatar.cc/50?u={{auth()->id()}}"
        width="50" height="50" alt=""
        class="rounded-full "
        >
        <h2 class="ml-4 font-semibold">Want to participate?</h2>
    </header>

    <div class="mt-4">
        <textarea
        class="w-full p-2 text-sm focus:outline-none focus:ring"
        name="body"
        rows="5"
        placeholder="Quick,think of something to say!"
        ></textarea>

        <x-form.errors name="body"/>
    </div>
    <div class="flex justify-end mt-6 pt-6 border-t border-gray-200 ">

        <x-form.button id="submit-button">Publish</x-form.button>
    </div>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<script>
    document.getElementById('submit-button').addEventListener("click", function(event){
        event.preventDefault()

        axios.post('/books/{{$book}}/comments', {
       })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });

    })

</script>

i get this error 404 (Not Found) !!

0 likes
29 replies
Sinnbeck's avatar

What is $book on that page ? The id of a book?

Did you mean to do

        axios.post('/books/{{$book->id}}/comments', {
Sinnbeck's avatar

@mutaz what is the url it calls? Check the network tab in dev tools (f12)

Sinnbeck's avatar

@mutaz why did you wrote 404 if it was 422 before?

show the controller method . You don't post any data so that is most likely the problem

mutaz's avatar
Level 7

@Sinnbeck

 public function store(Book $book)
    {
        request()->validate([
            'body' => 'required|max:255'
        ]);

        $book->comments()->create([
            'user_id' => 1,
            'body' => 'hie ',
        ]);

        return back()->with('flash', 'Commented Successfully');
    }
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@mutaz you expect body, but don't send any data at all. Axios does not automatically grab your form data. You need to pass it to it (the {} part)

mutaz's avatar
Level 7

@Sinnbeck thanks a lot thats useful , sorry for disturbance advise me where the best to learn axios ?

Sinnbeck's avatar

@mutaz the axios part is fine. You now need to grab the data from the textarea. Are you using any js libraries or?

Sinnbeck's avatar

@mutaz no worries. Add an ID to the text area

        <textarea
        id="body"
        class="w-full p-2 text-sm focus:outline-none focus:ring"
        name="body"
        rows="5"
        placeholder="Quick,think of something to say!"
        ></textarea>

And grab the content

var body = document.getElementById('body').value 
axios.post('/books/{{$book->id}}/comments', {body: body} 
1 like
mutaz's avatar
Level 7

@Sinnbeck ohh thank u very much that what i really want , i need to imporve js

Sinnbeck's avatar

@mutaz happy to help. Google is your friend for most of these things

2 likes
mutaz's avatar
Level 7

@nouraa where is your forum for error, could I help you

1 like
nouraa's avatar

@mutaz yes thanks

export default function Login() {

const { setCurrentUser, setUserToken } = useStateContext(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState({__html: ''});

const onSubmit = (ev) => { ev.preventDefault(); setError({ __html: "" });

axiosClient
.post('/login', {
  email,
  password,
})
.then(({ data }) => {
  setCurrentUser(data.user)
  setUserToken(data.token)
})
.catch((error) => {
  if (error.response) {
    const finalErrors = error.response.data.errors ? Object.values(error.response.data.errors) : [].reduce((accum, next) => [...accum, ...next], [])
    setError({__html: finalErrors.join('<br>')})
  }
  console.log(error)
});

};

this is my code: the console tells that the error is in the .post line

mutaz's avatar
Level 7

@nouraa you can modify the line to use an initial value for the reduce() function. For example, you can provide an empty array as the initial value:

const finalErrors = error.response.data.errors ? Object.values(error.response.data.errors).reduce((accum, next) => [...accum, ...next], []) : [];

This modification ensures that even if error.response.data.errors is undefined or null, the reduce() function will still receive an initial array ([]) and concatenate the accumulated and next values correctly.

1 like
mutaz's avatar
Level 7

@nouraa could you show me the validation and the route request for that..

1 like
nouraa's avatar

@mutaz I don't understand what is the validation, and do you mean by the route this line?

Route::post('/login', [AuthController::class, 'login']);

nouraa's avatar

@mutaz can you give me your contact so I will give you access to my computer then you can help?

mutaz's avatar
Level 7

@nouraa i mean the Authcontroller the login method what type of contact that you want ?

nouraa's avatar

@mutaz public function login(LoginRequest $request) { $credentials = $request->validated(); $remember = $credentials['remember'] ?? false; unset($credentials['remember']);

    if (!Auth::attempt($credentials, $remember)) {
        return response([
            'error' => 'The Provided credentials are not correct'
        ], 422);
    }
    $user = Auth::user();
    $token = $user->createToken('main')->plainTextToken;

    return response([
        'user' => $user,
        'token' => $token
    ]);
}

for the contact, email or Whatsapp or whatever you want

mutaz's avatar
Level 7

@nouraa this is for Whatsapp +972595191692,

can you dd($token) to see the method gnerate it or not

NoLAstNamE's avatar

@nouraa If I were you, I'll post this as a "New Discussion". And also, when showing your code, wrap them in triple backticks (`).

Here's an example:

```

// your code here

```

One more thing, include all the necessary code in one question, and don't add them in the comment one by one.

Please or to participate in this conversation.