https://qiita.com/acro5piano/items/f33381fc60408abe9865
このページを参考にlaravel
とVue.js
でアプリを作成しています。
Vue側で作成したAPIでDBからデータをとってくることができません。
わかる方がいらっしゃいましたご教示ください。
下記はVueのコンポーネントになります。
Vue
1<template> 2 <div class="notice-field"> 3 <div class="room-title">お知らせ</div> 4 <div v-for="notice in notices"> 5 {{ notice.title }} 6 {{ notice.text }} 7 </div> 8 </div> 9</template> 10 11<script> 12export default { 13 created() { 14 this.getNotices() 15 }, 16 data() { 17 return { 18 notices: [] 19 } 20 }, 21 methods: { 22 getNotices() { 23 this.$http.get('/api/getNotices') 24 .then(res => { 25 this.notices = res.data 26 }) 27 } 28 } 29} 30</script>
下記はroutes/api.php
のDBにアクセスするコードになります。
php
1 2Route::group(['middleware' => 'api'], function() { 3 Route::get('notices', function() { 4 $notices = Notice::all()->take(5); 5 return $notices; 6 }); 7});
axios
の設定は以下になります。
bootstrap
1import Vue from 'vue' 2 3window._ = require('lodash'); 4 5try { 6 window.Popper = require('popper.js').default; 7 window.$ = window.jQuery = require('jquery'); 8 9 require('bootstrap'); 10} catch (e) {} 11 12window.axios = require('axios') 13 14window.axios.defaults.headers.common = { 15 'X-CSRF-TOKEN': window.Laravel.csrfToken, 16 'X-Requested-With': 'XMLHttpRequest' 17} 18 19Vue.prototype.$http = window.axios 20 21let token = document.head.querySelector('meta[name="csrf-token"]'); 22 23if (token) { 24 window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; 25} else { 26 console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); 27}
回答1件
あなたの回答
tips
プレビュー