2
votes

I am creating a simple CRUD operations in laravel by using Vue js along with vue axios and vue router. Routing is working fine as expected but the issue is when i have save the data by using axios the response i get is 401 unauthorized. I have protected my route just like this in web.php

Route::get('/{any}', function () {
    return view('posts');
  })->where('any', '.*')->middleware(['auth']);

And in api.php i have routes like this.

Route::post('/quiz/create-quiz-category', 'QuizCategoryController@store')->middleware(['auth']);

I am currently using laravel default auth system. Below is my vue component script code.

this.axios.post(uri, {post: this.post}, {
          headers: {
              'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
              'Accept' : 'application/json'
          }
        }).then((response) => {
        // this.$router.push({name: 'home'});
        });

I appreciate if someone tell me that what wrong with code, and i am not currently using any passport or jwt.

Thanks.

1
Possible duplicate of this one.Benjamin Beganović
@BenjaminBeganović I have tried the above ticket solution, But now its simplet did not open page because of 404 error.Bilal Ahmed
Remove / from the api. Put 'quiz/create-quiz-category'Luca Rossi
Auth middleware requires Authorization header with token present in it and the middleware in api.php will be auth.apiankith vishwakarma
Thanks i will try the best possibility and let you guys know.Bilal Ahmed

1 Answers

0
votes

api_token: this.user.api_token

         axios.post("http://foo",
         {headers: { 'Authorization' : 'Bearer '+ api_token}})
         .then(response => {
                    //action
                })

link: https://forum.vuejs.org/t/401-unauthorized-vuejs-laravel-and-passport/59770

or

       postComment() {
      axios.post('/api/posts/'+this.post.id+'/comment', {
        api_token: this.user.api_token,
        body: this.commentBox
      })

but make sure that you have "user.api_token"