ajsmith_codes's avatar

401 Unauthorized when trying to update through Axios.

Laravel 7, Vue, Bootstrap-vue, Coreui Laravel admin template, Spatie Auth.

I can get data via Axios, but can't seem to post.

In my vue component:

    updateUser() {
        console.log('Editing data');
        this.form.put('api/user/' + this.form.id)
            .then(() => {
     
                $('#addNew').modal('hide');
                $emit('AfterCreate');
            })
            .catch(() => {
                this.$Progress.fail();
            });
    },

URL in the PUT is: 127.0.0.1:8000/api/user/1

API Route file: Route::apiResources(['user' => 'API\UserController']);

0 likes
25 replies
ajsmith_codes's avatar

@automica I did try adding that, but no luck. Bootstrap includes a token for API requests, doesn't it? Or am I misunderstanding that?

automica's avatar

@ajsmith_codes if it’s hitting the endpoint and erroring then you should have something in your logs as to what the error is. If it’s not erroring but also not saving then have you checked you have added the field you are trying to save in the fillable array in your model?

ajsmith_codes's avatar

@automica I think the 401 error has to do with the authentication in the Coreui files. I moved the route outside of that and into the web routes, and now I get this error:

405, Method not allowed.

I changed the code a bit:

        axios.post('user/'  + this.form.id + '/update')
            .then((response) => {
                $('#success').html(response.data.message)
                $('#addNew').modal('hide');
                window.location.reload()
            })
            .catch(error => {
                console.log(error)
            });

And the web route:

Route::patch('user/{id}/update', 'UserController@update');

MarianoMoreyra's avatar

Hi @ajsmith_codes

Try adding a slash at beginning of your url, just in case you are not calling from a url at the root:

this.form.put('/api/user/' + this.form.id)

Although I don't believe that's the problem, or you should be getting a 404 instead of 401 a guess...but anyway, it doesn't hurt to add that slash as a good practice :)

MarianoMoreyra's avatar

@ajsmith_codes well you changed the code just before I hit submit to my reply hehe

Now you are getting a 405 error because you are doing a POST request and your route is a PATCH one

ajsmith_codes's avatar

@marianomoreyra I just changed it to axios.patch. I also ended up changing the URL to '/user/{id}/update'.

The error I get now is 422 Unprocessable Entity. I'll need to research that further. Have you come across that error?

ajsmith_codes's avatar

@sinnbeck Yes, it appears that nothing is passing when I submit. I am using a modal window to bring up the user details. Here are the two inputs:

                        <div
                            class="form-group">
                            <input
                                v-model="form.email"
                                type="email"
                                name="email"
                                placeholder="Email Address"
                                class="form-control"
                                :class="{ 'is-invalid': form.errors.has('email') }">
                        </div>

EDIT: And here is the method:

    updateUser(e, user) {
        console.log('Editing data');
        if (this.name) {
            axios.patch('/user/' + this.form.id + '/update', {
                user
            })
                .then((response) => {
                    $('#success').html(response.data.message)
                    $('#addNew').modal('hide');
                    window.location.reload()
                })
                .catch(error => {
                    console.log(error)
                });
        }

    },
MarianoMoreyra's avatar

@ajsmith_codes inspect the Request to see what are you sending to Laravel, or the Response to see what validation errors are you getting

MarianoMoreyra's avatar

@ajsmith_codes also try passing this.userobject without surrounding braces.

Like this:

    updateUser(e, user) {
        console.log('Editing data');
        if (this.name) {
            axios.patch('/user/' + this.form.id + '/update', 
                this.user
            )
                .then((response) => {
                    $('#success').html(response.data.message)
                    $('#addNew').modal('hide');
                    window.location.reload()
                })
                .catch(error => {
                    console.log(error)
                });
        }

    },
ajsmith_codes's avatar

@marianomoreyra Sorry, yes, I tried that. It doesn't fire because this.name appears to be empty. For some reason, I'm not getting the value to pass.

If I take out the if (this.name) part, I get this in the response: {"message":"The given data was invalid.","errors":{"name":["The name field is required."],"email":["The email field is required."]}}

Which also makes me think the value isn't passing.

ajsmith_codes's avatar

@marianomoreyra I get undefined. If I do this:

console.log(this.form.name);

I finally get the data. How do I pass it to the controller?

I have tried name: this.name name: this.form.name

Both come back with unprocessable Entity.

MarianoMoreyra's avatar

@ajsmith_codes but why you ask for this.name and then pass user to axios? Isn’t name an attribute of user in which case you should ask for this.user.name instead?

ajsmith_codes's avatar

@marianomoreyra I changed it to this.user.name and get:

Cannot read property 'name' of undefined.

I took user out because it appears that as long as you use "this", you don't need to.

MarianoMoreyra's avatar
Level 25

@ajsmith_codes I'm sorry, just read your entire reply.

In this case, then you should pass it as an object:

    updateUser(e, user) {
        console.log('Editing data');
        if (this.name) {
            axios.patch('/user/' + this.form.id + '/update', 
                { name: this.form.name, email: this.form.email }
            )
                .then((response) => {
                    $('#success').html(response.data.message)
                    $('#addNew').modal('hide');
                    window.location.reload()
                })
                .catch(error => {
                    console.log(error)
                });
        }

    },
ajsmith_codes's avatar

@marianomoreyra Getting closer! Now I get: The PATCH method is not supported for this route.

Here is my route:

Route::patch('/user/{id}/update', 'UsersController@update');

MarianoMoreyra's avatar

@ajsmith_codes check that you don’t have another route with the same signature (/user/{id}/update) with something different than patch

MarianoMoreyra's avatar

But have you changed anything in between? Because before it was accepting that route and giving you a validation error. Something else must have changed in between

ajsmith_codes's avatar

Your code got us a bit farther. I found a second route configured. Once I removed that, I got to another error: Route [dashboard.admin.usersList] not defined. Working on figuring that one out.

EDIT: This is in the controller update:

return redirect()->route('dashboard.admin.usersList');

ajsmith_codes's avatar

It's working! Thanks to everyone for your help. The final piece after @marianomoreyra made changes was to do with the route. I was trying to redirect, but all I needed was to close the modal window.

Please or to participate in this conversation.