#javascript #php #mysql #laravel #vue.js
#javascript #php #mysql #laravel #vue.js
Вопрос:
Я работал над адресной книгой, используя Laravel и vue. Мои представления работают правильно, но я продолжаю получать ошибку 404 not found при попытке получить доступ к данным в базе данных. Я перепробовал так много вещей, но мне чего-то не хватает, и я не уверен, что я делаю неправильно.
Мои контакты просмотр:-
<template>
<div>
<h3 class="text-center">All contacts</h3><br/>
<table class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
<th>Birthday</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="contact in contacts" :key="contact.id">
<td>{{ contact.firstNamr }}</td>
<td>{{ contact.lastName }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td>{{ contact.birthday }}</td>
<td>
<div class="btn-group" role="group">
<router-link :to="{name: 'createAddress', params: { id: contact.id }}" class="btn btn-primary">createAddress
</router-link>
<router-link :to="{name: 'editContact', params: { id: contact.id }}" class="btn btn-primary">Edit
</router-link>
<button class="btn btn-danger" @click="deleteContact(contact.id)">Delete</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
contacts: []
}
},
created() {
this.axios
.get('http://localhost:8000/api/contacts/')
.then(response => {
this.contacts = response.data;
});
},
methods: {
deleteContact(id) {
this.axios
.delete(`http://localhost:8000/api/deleteContact/${id}`)
.then(response => {
let i = this.contacts.map(item => item.id).indexOf(id); // find index of your object
this.contacts.splice(i, 1)
});
}
}
}
</script>
App.js
require('./bootstrap');
window.Vue = require('vue');
import App from './App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './router';
Vue.use(VueRouter);
Vue.use(VueAxios, axios);
const router = new VueRouter({
mode: 'history',
routes: routes
});
const app = new Vue({
el: '#app',
router: router,
render: h => h(App),
});
Router.js
import Contacts from './contacts.vue';
import CreateContact from './createContact.vue';
import EditContact from './editContact.vue';
import Details from './details.vue';
export const routes = [
{
name: 'home',
path: '/',
component: Contacts
},
{
name: 'createContact',
path: '/createContact',
component: CreateContact
},
{
name: 'editContact',
path: '/editContact/:id',
component: EditContact
},
{
name: 'details',
path: '/details/:id',
component: Details
},
];
API.js
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('contacts', 'ContactController@index');
Route::group(['prefix' => 'contact'], function () {
Route::post('/createContact', 'ContactController@createContact');
Route::get('editContact/{id}', 'ContactController@editContact');
Route::post('updateContact/{id}', 'ContactController@updateContact');
Route::delete('deleteContact/{id}', 'ContactController@deleteContact');
});
web.php
<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//
Route::get('{any}', function () {
return view('app');
})->where('any', '.*');
Route::get('app/contacts', 'ContactController@index');
Route::group(['prefix' => 'contact'], function () {
Route::post('app/createContact', 'ContactController@createContact');
Route::get('app/editContact/{id}', 'ContactController@editContact');
Route::post('app/updateContact/{id}', 'ContactController@updateContact');
Route::delete('app/deleteContact/{id}', 'ContactController@deleteContact');
});
Contact Controller
public function index()
{
$contact = Contact::orderBy('id', 'desc')->get();
return $contact;
}
У меня также возникли проблемы с заполнением данных. Я могу ввести его, используя необработанный код SQL, но я все еще не могу получить данные из базы данных.
Комментарии:
1. Вы уверены, что правильно обращаетесь к маршрутам? Выполните a
php artisan route:list
, чтобы проверить все ваши маршруты. Может быть проблема с префиксами, также может быть проблема с чувствительностью к регистру в URL-адресах.2. Вы были правы, мне не нужен /{id} в конце любого из маршрутов в web.php
Ответ №1:
Я вызывал api / в vue и app / в маршрутизаторе.
Ответ №2:
Вы добавили правильное имя базы данных в .env-файл?