具有 Laravel 5.4 后端的 Vuejs 2,post(未经授权)错误

Vuejs 2 with Laravel 5.4 backend, post (Unauthorized) error

我正在学习 Vuejs 2,并构建一个客户目录应用程序以供娱乐和测试,Laravel 5.4 作为后端 (api),带有 Cors 和 Passport 包。和 Vuejs 作为 vue-router 和 axios 的前端我能够登录并将令牌存储在 cookie 中我得到了所有客户而没有任何错误,但是当我尝试创建新客户时我在控制台中收到以下错误POST http://localhost:8000/api/customer 401(未经授权) 网络 {"error":"Unauthenticated."}。如果我评论 auth:api 中间件,我可以 post 没有任何错误。

routes/api.php

      Route::get('/', 'CustomerCtrl@index');
   Route::get('customer/{id}', 'CustomerCtrl@show');
Route::post('customer', 'CustomerCtrl@store');
Route::delete('customer/{id}', 'CustomerCtrl@destroy');
Route::put('customer/{id}', 'CustomerCtrl@update');

CustomerCtrl.php

<?php

namespace App\Http\Controllers;

use App\Customer;
use Illuminate\Http\Request;

class CustomerCtrl extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function index()
    {
        return response()->json(Customer::all(), 200);
    }

    public function show($id)
    {
        return response()->json(Customer::findOrFail($id), 200);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
          'first_name' => 'required',
          'last_name' => 'required',
          'email' => 'required|email',
          'phone' => 'required',
          'address' => 'required',
          'country' => 'required',
        ]);
        Customer::create($request->all());
        return response()->json('Customer Created', 200);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
          'first_name' => 'required',
          'last_name' => 'required',
          'email' => 'required|email',
          'phone' => 'required',
          'address' => 'required',
          'country' => 'required',
        ]);
        $customer = Customer::findOrFail($id);
        $customer->update($request->all());
        return response()->json('Customer Updated', 200);
    }

    public function destroy(Request $request, $id)
    {
        $customer = Customer::findOrFail($id);
        $customer->forceDelete();
        return response()->json('Customer Deleted', 200);
    }
}

新客户组件(vuejs)

<template>
<div class="add-customer">
  <h1 class="page-header">Add Customer</h1>
  <div v-if="isErrors" class="alert alert-danger">
    <ul>
      <li v-for="error in errors">
        {{error[0]}}
      </li>
    </ul>
  </div>
  <form @submit.prevent>
    <div class="form-group">
      <label for="firstName">First Name</label>
      <input type="text" id="firstName" v-model="first_name" class="form-control">
    </div>
    <div class="form-group">
      <label for="lastName">Last Name</label>
      <input type="text" id="lastName" v-model="last_name" class="form-control">
    </div>
    <div class="form-group">
      <label for="email">Email</label>
      <input type="text" id="email" v-model="email" class="form-control">
    </div>
    <div class="form-group">
      <label for="Phone">Phone</label>
      <input type="text" id="Phone" v-model="phone" class="form-control">
    </div>
    <div class="form-group">
      <label for="country">Country</label>
      <input type="text" id="country" v-model="country" class="form-control">
    </div>
    <div class="form-group">
      <label for="address">Adress</label>
      <textarea type="text" id="address" v-model="address" class="form-control" rows="3"></textarea>
    </div>
    <div class="form-group">
      <button @click.prevent="addCustomer" class="btn btn-primary">Submit</button>
    </div>
  </form>
</div>
</template>

<script>
export default {
  name: 'add-customer',
  data() {
    return {
      first_name: '',
      last_name: '',
      address: '',
      phone: '',
      country: '',
      email: '',
      errors: {},
      isErrors: false
    }
  },
  head: {
    title: {
      inner: 'Add Customer'
    },
  },
  methods: {
    addCustomer() {
      this.$http.post('http://localhost:8000/api/customer', {
        headers: {
           'Authorization':'Bearer ' + this.$cookie.get('token')
        },
        first_name: this.first_name,
        last_name: this.last_name,
        address: this.address,
        phone: this.phone,
        country: this.country,
        email: this.email
      }).then(res => {
        console.log(res);
        this.$router.push({
          name: 'Customers'
        })
      }).catch(res => {
        this.isErrors = true;
        this.errors = res.response.data;
        console.log(res);

      });
    }
  }
}
</script>
<style scoped>

</style>

Login.vue分量

  methods: {
    login() {
      const data = {
        client_id: 4,
        client_secret: '55bC4Ud1ariLqnHSk1fxKiKHF8FDI8NTWHR5d13k',
        grant_type: 'password',
        username: this.email,
        password: this.password

      }
      this.$http.post('http://localhost:8000/oauth/token/', data).then(res => {
        console.log(res);
        this.$cookie.set('api_token', res.data.access_token, 1);
        this.$router.push({
          name: 'Customers'
        })
      }).catch(res => {
        this.isErrors = true;
        this.errors = res.response.data;
        console.log(res);
      });
    }
  }

使用 xsrf 令牌或将以下内容添加到 api/app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    'customer',
    'customer/*'
    'customer/*'
];

这将禁用 xsrf 令牌。请谨慎使用。

通过在 main.js (Vue) 中定义默认的 axios baseurl 和 headers 解决了:)。

main.js

axios.defaults.baseURL = 'http://localhost:8000/api';
axios.defaults.headers.common['Authorization'] = "Bearer " + 
VueCookie.get('api_token');

并删除了所有组件中所有本地定义的 headers。