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

带有Laravel 5.4后端的Vuejs 2,post(未经授权)错误,laravel,vue.js,axios,Laravel,Vue.js,Axios,我正在学习Vuejs 2,并构建一个客户目录应用程序,用于娱乐和测试,Laravel 5.4作为后端(api),带有Cors和Passport包。Vuejs作为vue router和axios的前端,我能够登录并将令牌存储在cookie中,我获得了所有客户的信任,没有任何错误,但当我尝试创建新客户时,我在控制台POST 401(未经授权)中网络{“错误”:“未经身份验证”。}。如果我对auth:api中间件进行注释,我就可以发布而不会出现任何错误 路由/api.php Route::

我正在学习Vuejs 2,并构建一个客户目录应用程序,用于娱乐和测试,Laravel 5.4作为后端(api),带有Cors和Passport包。Vuejs作为vue router和axios的前端,我能够登录并将令牌存储在cookie中,我获得了所有客户的信任,没有任何错误,但当我尝试创建新客户时,我在控制台POST 401(未经授权)中网络{“错误”:“未经身份验证”。}。如果我对auth:api中间件进行注释,我就可以发布而不会出现任何错误

路由/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');
<?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);
    }
}
CustomerCtrl.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');
<?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);
    }
}

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

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

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

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

protected $except = [
    'customer',
    'customer/*'
    'customer/*'
];
这将禁用xsrf令牌。请谨慎使用。

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

main.js

<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>
axios.defaults.baseURL = 'http://localhost:8000/api';
axios.defaults.headers.common['Authorization'] = "Bearer " + 
VueCookie.get('api_token');
并删除了所有组件中所有本地定义的头。

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

main.js

<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>
axios.defaults.baseURL = 'http://localhost:8000/api';
axios.defaults.headers.common['Authorization'] = "Bearer " + 
VueCookie.get('api_token');

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

我认为这种实现是不对的,它只起作用,因为您删除了该路由的所有CSRF令牌验证,这反过来会打开XSS的OPs代码,如果他的下一个POST请求是文件上传,而不是用户自己的上传,那么在化身中这将是一个麻烦,但在更重要的事情上,比如加密硬币应用程序,那将是可怕的。@clusterBuddy你说得110%对。这不是做事的首选方式。最好使用XSRF令牌。我不认为这个实现是正确的,它只起作用,因为您删除了该路由的所有CSRF令牌验证,这反过来会打开XSS的OPs代码,如果他的下一个POST请求是文件上传,而不是用户自己的上传,在头像中这将是一个麻烦,但在更重要的事情上,比如说加密硬币应用程序,那将是可怕的。@clusterBuddy你说得110%对。这不是做事的首选方式。最好使用XSRF令牌。将应用程序部署到主机时,我应该怎么做?使用
axios
调用
htt://localhost:8000/
?我应该像这样更改链接或smth吗?@是的,你应该更改链接。用于不同的环境。我在后端使用
Laravel 5.4
,并将
MySQL
用作数据库。我应该如何更改API链接?将应用程序部署到主机时应该怎么做?使用
axios
调用
htt://localhost:8000/
?我应该像这样更改链接或smth吗?@是的,你应该更改链接。用于不同的环境。我在后端使用
Laravel 5.4
,并将
MySQL
用作数据库。我应该如何更改API链接?