Carl Angelo Orale
Carl Angelo Orale

Reputation: 182

Nuxt.js and Laravel Api - 422 Displaying Error instead of Forms

[Error][1]

Hi Team,

Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this. Here is my php code


return response()->json([
                'errors' => [
                    'email' => ['Sorry we cant find you with those details.'],
                ],
            ], 422);

Javascript

 async submit() {
                await this.$auth.loginWith("local", {
                    data: this.form
                })

Upvotes: 1

Views: 2038

Answers (2)

Stuart Pearman
Stuart Pearman

Reputation: 139

This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:

async handleSubmit() {
    try {
        const authResponse = await this.$auth.loginWith('local', { 
            data: this.formData
        });
        const { status, data } = authResponse;

        if (status === 200) 
            this.createFlashAlert({ 'success': 'Login successful' });
    } catch (error) {
        if (error.response.status === 422)
            this.createFlashAlert(error.response.data);
    }
}

So the checklist:

  1. Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
  2. in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.

If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.

Upvotes: 1

Salam
Salam

Reputation: 1168

In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.

try {

  await this.$auth.loginWith("local", {
    data: this.form
  })

} catch (e) {

  return;
}

Upvotes: 2

Related Questions