laravel - 带有 Laravel 5.4 后端的 Vuejs 2,发布(未经授权)错误

标签 laravel vue.js axios

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

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

最佳答案

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

ma​​in.js

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

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

关于laravel - 带有 Laravel 5.4 后端的 Vuejs 2,发布(未经授权)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44205221/

相关文章:

mocking - 使用 axios 构造函数时模拟 axios

javascript - 如何在 Axios GET 请求中组合异步和非异步选项

node.js - 使用 Vue 处理来自 Express API 的错误

php - 试图从管理系统注销特定用户 : Laravel 5. 2.37

php - CRUD Laravel 4如何链接销毁?

php - Laravel eloquent - 防止连接表时覆盖值

javascript - 如何在 Vue JS 中添加 window.addEventListener 和删除 window.removeEventListener

mysql - 什么对性能和可读性更好 : a status column with boolean type or varchar?

javascript - 使用 Vue.js 的异步/等待 axios 调用

javascript - 在 vue.js 中更改文件输入