【问题标题】:laravel user api_token is undefinedlaravel 用户 api_token 未定义
【发布时间】:2018-10-11 10:28:07
【问题描述】:

我在尝试用axios 发表新评论时收到'unauthorized' 错误 ..... 我在@987654325 中的axios.post 之前添加了(console.log(this.user.api_token);) @ 方法 。输出是:"undefined" !!!!!!!!!! 我正在学习,我对api的了解不多。但我不认为用户api_token 是手动设置的。还是它???

脚本:

<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::get('/post/{post}', 'CommentController@index');
    Route::middleware('auth:api')->group(function () {
      Route::post('/post/{post}', 'CommentController@store');
     });

评论控制器

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;
}

【问题讨论】:

    标签: json laravel vue.js token axios


    【解决方案1】:

    如果您尝试从 vuejs 使用自己的 api,则无需手动设置 api 令牌。只需更新 app/Http/Kernel.php 中的 web 中间件组以包含此行:

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

    此中间件将附加一个 laravel_token cookie,其中包含一个加密的 JWT,Passport 将使用它来验证来自您的 JavaScript 应用程序的 API 请求。

    在此处阅读更多信息:https://laravel.com/docs/5.6/passport#personal-access-tokens

    但是,如果您从外部来源(如移动应用程序)使用相同的 api,则护照将需要 api 令牌来验证请求。可以在用户登录或注册时创建令牌。方法如下:

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

    然后在向api发起请求的时候给axios添加一个headers对象

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

    在此处阅读更多信息:https://laravel.com/docs/5.6/passport#managing-personal-access-tokens

    【讨论】:

    • 我正在尝试使用 Request::create() 从另一个控制器使用我自己的 api,但它响应未经授权
    • 你为什么要这样做?如果您已经在控制器中,您应该能够执行您需要的任何操作。
    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 2017-07-23
    • 2016-11-24
    • 2018-07-10
    • 2021-06-29
    • 2020-07-23
    • 2016-11-10
    • 2019-10-28
    相关资源
    最近更新 更多