フロントエンドVuex・NuxtjsとRails間をajax通信でやり取りしたいのですが、サーバ起動すると、
Access to XMLHttpRequest at 'http://localhost:3100/todo/index' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
オリジンのエラーが表示されます。
ポートを変えたり、localhost
や0.0.0.0
とアドレスも変えてみましたが、同様のエラーでした。
ディレクトリ構造が問題でしょうか。
Railsは/document/ruby/プロジェクト名
Vuexは/document/vue/vuex/プロジェクト名
となっています。
RailsからはJSONで渡しています。
オリジンエラーの解決策がわかりません。ご教授いただけると幸いです。
また、この影響なのかミューテーション後、/pages/index.vueからstateのtodos
にアクセスすると、コミットしたはずの値が空で返されるのですが、関係あるのでしょうか。
ソースコード
/pages/index.vue
javascript
1<template> 2 <div v-for="todo in todos" :key="todo.id"> 3 <p>{{ todo.title }}</p> 4 </div> 5</template> 6 7<script> 8 import { mapState, mapMutations, mapGetters } from 'vuex' 9 import axios from 'axios' 10 11export default { 12 computed: { 13 ...mapState({ 14 todos: 'todos' 15 }), 16 ...mapGetters({ 17 todos: 'todos' 18 }) 19 }, 20 created () { 21 this.todos() 22 }, 23</script>
/store/index.js
javascript
1import Vuex from 'vuex' 2import axios from 'axios' 3 4const store = () => { 5 return new Vuex.Store({ 6 state: { 7 todos: [], 8 }, 9 getters: { 10 todos: state => { 11 return state.todos 12 } 13 }, 14 actions: { 15 todos ({ commit }) { 16 axios.get('http://localhost:3100/todo/index') 17 .then((res) => { 18 commit('todos', res.data) 19 }) 20 } 21 }, 22 mutations: { 23 todos (state, lists) { 24 state.todos = lists 25 // ここでコンソールログを見ると、stateへ正常に代入されている 26 } 27 } 28 29export default store
Rails
/app/controllers/todo_controller.rb
ruby
1class TodoController < ApplicationController 2 def index 3 @todos = Todo.all 4 render json: @todos 5 end 6end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/08 16:43