简体   繁体   中英

laravel user api_token is undefined

i'm getting the 'unauthorized' error when trying to post a new comment with axios ..... i added ( console.log(this.user.api_token); ) just before axios.post in postComment() method . the output is : "undefined" !!!!!!!!!! i'm learning and i don't know much about api's . but i don't think user api_token is to be set up manually .or does it ???

the script :

<script>

const app = new Vue({
  el: '#app',
  data: {
    comments: {},
    commentBox: '',
    post: {!! $post->toJson() !!},
    user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
  },
  mounted() {
    this.getComments();
  },
  methods: {
    getComments() {
      axios.get('/api/post/'+this.post.id)
            .then((response) => {
              this.comments = response.data
            })
            .catch(function (error) {
              console.log(error);
            });
    },
    postComment() {
        console.log(this.user.api_token);

      axios.post('/api/post/'+this.post.id , {
        api_token: this.user.api_token,
        body: this.commentBox
      })
      .then((response) => {
        this.comments.unshift(response.data);
        this.commentBox = '';
      })
      .catch((error) => {
        console.log(error);
      })
    }
  }
})

api route

    Route::get('/post/{post}', 'CommentController@index');
    Route::middleware('auth:api')->group(function () {
      Route::post('/post/{post}', 'CommentController@store');
     });

CommentController

public function index(Post $post){
  return response()->json($post->comments()->with('user')->get());
 }

public function store(Request $req,Post $post){
   $comment=$post->comment()->create([
       'user_id'=>auth::id(),
       'body'=>$req->body
   ]);
   $comment=Comment::where('id',$comment->id)->with('user')->first();
    return $comment->toJson;
}

If you are trying to consume your own api from vuejs there's no need to set the api token manually. Just update the web middleware group in app/Http/Kernel.php to include this line:

\\Laravel\\Passport\\Http\\Middleware\\CreateFreshApiToken::class

This middleware will attach a laravel_token cookie that contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application.

Read more here: https://laravel.com/docs/5.6/passport#personal-access-tokens

But, if you are consuming this same api from an external source like a mobile app, an api token will be required by passport to authenticate the request. The token can be created when the user is logged in or registered. Here's how:

//create a token $token = $user->createToken('Token Name')->accessToken;

Then add an headers object to axios when making a request to the api

axios({
  method: 'method',
  url: 'url',
  headers: {
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$token
  }
})
.then()
.catch()

Read more here: https://laravel.com/docs/5.6/passport#managing-personal-access-tokens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM