Laravel (vue и vuex) Добавление данных всегда возвращает неавторизованный - PullRequest
0 голосов
/ 21 сентября 2019

В настоящее время я делаю сайт, который использует Laravel, который обрабатывает бэкэнд, Vuejs, который обрабатывает фронтенд, и Vuex, который обрабатывает CRUD Axios.Для своей аутентификации я не использовал стандартное значение, которое предоставляет laravel, вместо этого я использую паспорт laravel.

Я пытался добавить данные в базу данных mysql, но, к сожалению, я всегда получаю эту ошибку.

сообщение Неаутентифицировано .

Я не знаю, как исправить ошибку или определить причину ошибки.

Коды

cycle.js (Vuex)

const actions = {
addCycle(context, cycle){
        axios.post('/cycle',{
            date_loading: cycle.date_loading,
            chicken_population: cycle.chicken_population,
            clean_up: cycle.clean_up,
            date_harvest: cycle.date_harvest,
            date_manure_collection: cycle.date_manure_collection,
            date_cleaning: cycle.date_cleaning,
            date_disinfection: cycle.date_disinfection,
            date_rest: cycle.date_rest,
            date_next_loading: cycle.date_next_loading,
        })
        .then(response =>{
            context.commit('addCycle',response.data)
        })
        .catch(error =>{
            console.log(error)
    })  
    },
}

ModalAddCycle.vue

<template>
  <div
    class="modal fade"
    id="modalAddCycle"
    tabindex="-1"
    role="dialog"
    aria-labelledby="modalTitle"
    aria-hidden="true"
  >
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <ValidationObserver v-slot="{ invalid, passes, validate }">
          <form @submit.prevent="passes(createCycle)">
            <div class="modal-header">
              <h5 class="modal-title" id="modalTitle">Add Cycle</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="color-close" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="form-group pl-2 pr-2">
                <ValidationProvider
                  name="loading date"
                  mode="eager"
                  v-slot="{ classes, errors }"
                >
                  <label for="date_loading">Loading Date</label>
                  <div class="row">
                    <div class="col-9">
                      <v-date-picker
                        :class="classes"
                        v-model="date_loading"
                        id="date_loading"
                        title-position="left"
                        required
                      />
                    </div>
                    <div class="col ml-4">
                      <!-- <button class="btn btn-primary" type="button" @click="validate">Check</button> -->
                    </div>
                  </div>
                  <small class="form-text text-error">{{ errors[0] }}</small>
                </ValidationProvider>
              </div>
              <div class="form-group pl-2 pr-2">
                <ValidationProvider
                  name="chicken population"
                  mode="eager"
                  rules="numeric"
                  v-slot="{ classes, errors }"
                >
                  <label for="chicken_population">Chicken Population</label>
                  <input
                    :class="classes"
                    v-model="chicken_population"
                    id="chicken_population"
                    type="textr"
                    class="form-input"
                    required
                  />
                  <small class="form-text text-error">{{ errors[0] }}</small>
                </ValidationProvider>
              </div>
              <div class="form-group pl-2 pr-2">
                <ValidationProvider
                  name="clean up"
                  rules="numeric"
                  mode="eager"
                  v-slot="{ classes, errors }"
                >
                  <label for="clean_up">Clean up</label>
                  <input
                    :class="classes"
                    v-model="clean_up"
                    id="clean_up"
                    type="text"
                    class="form-input"
                    required
                  />
                  <small class="form-text text-error">{{ errors[0] }}</small>
                </ValidationProvider>
              </div>
              <div class="form-group pl-2 pr-2">
                <label for="date_harvest">Harvest Date</label>
                <input
                  :value="dateHarvest"
                  id="date_harvest"
                  readonly
                  class="form-control-plaintext ml-2"
                />
              </div>
              <div class="form-group pl-2 pr-2">
                <label for="date_manure_collection">Manure Collection Date</label>
                <input
                  :value="dateManureCollection"
                  id="date_manure_collection"
                  readonly
                  class="form-control-plaintext ml-2"
                />
              </div>
              <div class="form-group pl-2 pr-2">
                <label for="date_cleaning">Cleaning Date</label>
                <input
                  :value="dateCleaning"
                  id="date_cleaning"
                  readonly
                  class="form-control-plaintext ml-2"
                />
              </div>
              <div class="form-group pl-2 pr-2">
                <label for="date_disinfection">Disinfection Date</label>
                <input
                  :value="dateDisinfection"
                  id="date_disinfection"
                  readonly
                  class="form-control-plaintext ml-2"
                />
              </div>
              <div class="form-group pl-2 pr-2">
                <label for="date_rest">Rest Date</label>
                <input
                  :value="dateRest"
                  id="date_disinfection"
                  readonly
                  class="form-control-plaintext ml-2"
                />
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              <button type="submit" class="btn btn-success">Create</button>
            </div>
          </form>
        </ValidationObserver>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
name: "modalAddCycle";
export default {
  data() {
    return {
      date_loading: new Date(),
      chicken_population: "",
      clean_up: "",
      date_harvest: "",
      date_manure_collection: "",
      date_cleaning: "",
      date_disinfection: "",
      date_rest: ""
    };
  },
  methods: {
    ...mapActions(["addCycle"]),
    createCycle() {
      this.addCycle({
        date_loading: moment(this.date_loading).format("YYYY-MM-DD"),
        chicken_population: this.chicken_population,
        clean_up: this.clean_up,
        date_harvest: moment(this.date_loading).format("YYYY-MM-DD"),
        date_manure_collection: moment(this.date_loading).format("YYYY-MM-DD"),
        date_cleaning: moment(this.date_loading).format("YYYY-MM-DD"),
        date_disinfection: moment(this.date_loading).format("YYYY-MM-DD"),
        date_rest: moment(this.date_loading).format("YYYY-MM-DD")
      })
        .then(response => {
          toast.fire({
            type: "success",
            title: "Create cycle successfully!"
          });
          console.log()
          $("#modalAddCycle").modal("hide");
        })
        .catch(error => {
          swal.fire({
            type: "error",
            title: "There was something wrong!",
            text: error.response.data.message,
            showConfirmButton: false,
            timer: 3000
          });
        });
    }
  },
  computed: {
    dateHarvest() {
      this.date_harvest = moment(this.date_loading)
        .add(this.clean_up, "days").format("MM/DD/YYYY");
      return this.date_harvest;
    },
    dateManureCollection() {
      this.date_manure_collection = moment(this.date_harvest)
        .add(2, "days").format("MM/DD/YYYY")
      return this.date_manure_collection;
    },
    dateCleaning() {
      this.date_cleaning = moment(this.date_harvest)
        .add(9, "days").format("MM/DD/YYYY")
      return this.date_cleaning;
    },
    dateDisinfection() {
      this.date_disinfection = moment(this.date_harvest)
        .add(10, "days").format("MM/DD/YYYY")
      return this.date_disinfection;
    },
    dateRest() {
      this.date_rest = moment(this.date_harvest)
        .add(20, "days").format("MM/DD/YYYY")
      return this.date_rest;
    }
  }
};
</script>

CycleController.php

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {

    }

     public function store(Request $request)
        {
            // VALIDATION
            $this->validate($request, array(
                'date_loading' => 'required|date',
                'clean_up' => 'required|numeric',
                'chicken_population' => 'required|numeric',
            ));

            // STORING CYCLE DATA
            $storeCycle = Cycle::create([
                'date_loading' => request('date_loading'),
                'clean_up' => request('clean_up'),
                'chicken_population' => request('chicken_population'),
                'date_harvest' => request('date_harvest'), 
                'date_manure_collection' => request('date_manure_collection'), 
                'date_cleaning' => request('date_cleaning'),
                'date_disinfection' => request('date_disinfection'), 
                'date_rest' => request('date_rest'), 
                'date_next_loading' => request('date_next_loading'), 
                'user_id'     => Auth::id()   
            ]);

            // GETTING THE CYCLE ID
            $cycle = Cycle::where([
                ['date_loading',$request->get('date_loading')],
                ['date_harvest',$request->get('date_harvest')],
                ['user_id' => Auth::id()],
            ])->first();

            //CHECKS IF CYCLE DATA WAS EXISTED
            if($cycle){
            //STORING CHICKEN POPULATION IN POPULATION TABLE
            Population::create([
             'chicken_population'=> request('chicken_population'),
             'chicken_available'=> request('chicken_population'),
             'cycle_id' => $cycle->id ?? 0, 
             'user_id' => Auth::id() 
            ]);
            }
            return $storeCycle;


        }

api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::apiResources(['cycle' => 'API\CycleController']);

web.php

Route::get('/{any?}', function (){
    return view('layout');
})->where('any', '^(?!api\/)[\/\w\.-]*');

Ответы [ 2 ]

0 голосов
/ 22 сентября 2019

Не уверен, что ваша проблема такая же, но в репозитории laravel есть пиар, связанный с аналогичной ошибкой аутентификации API, которая может помочь.

https://github.com/laravel/laravel/pull/4764

Первоначальная проблема и объяснение перечислены в описании, но вот краткое изложение:

Хорошо, я изучил это, и я 'Я почти уверен, что это не имеет ничего общего с JSON или обработкой AuthenticationException, потому что AuthenticationException никогда даже не генерируется.Попробуйте сбросить $ request-> expectedJson () - это возвращает true?Вероятно, это так.

Эта строка действительно является проблемой.Он вызывается, когда родитель пытается создать исключение:

throw new AuthenticationException(
    'Unauthenticated.', $guards, $this->redirectTo($request)
);

Но маршрут входа в систему не существует по умолчанию, поэтому маршрут ('login') генерирует исключение InvalidArgumentException.

Эта ошибка присутствует даже в новой установке Laravel:

laravel new auth-test cd auth-test php artisan serve, а затем

curl -H "Accept: application/json" http://localhost:8000/api/user, и вы увидите то же исключение.

Эта ошибка, кажется, была введена в laravel/laravel@a14e623.

Обходной путь: Добавьте маршрут с именем "login" или удалите вызов на route('login') из Middleware.

0 голосов
/ 22 сентября 2019

Вам нужен паспортный токен для аутентификации javascript, и я цитирую: все, что вам нужно сделать, это добавить промежуточное программное обеспечение CreateFreshApiToken к вашей группе веб-промежуточного программного обеспечения в файле app / Http / Kernel.php:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

Для получения более подробной информации см. Документацию Laravel от здесь

Примечание: убедитесь, что модель пользователя использует Laravel\Passport\HasApiTokens trait

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...