I have a Rails 5.2.2 API that is serving JSON data at localhost:3000/v1/stories. I am trying to set up a Vuejs app to consume it with Axios. The rails terminal shows the request and throws no errors:
Started GET "/v1/stories" for 127.0.0.1 at 2018-12-19 18:06:44 -0500
Processing by V1::StoriesController#index as HTML
Story Load (0.8ms) SELECT "stories".* FROM "stories"
↳ app/controllers/v1/stories_controller.rb:6
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::JsonApi (6.25ms)
Completed 200 OK in 10ms (Views: 8.7ms | ActiveRecord: 0.8ms)
MyIn the vue app, I have the following relevant files:
Api.js retrieves the base connection:
import axios from 'axios'
export default() => {
return axios.create({
baseURL: `http://localhost:3000/v1`
headers: {
'Accept': 'applicaton/json',
'Content-Type': 'application/json'
}
})
}
StoriesService.js:
import Api from '@/services/Api'
export default {
fetchStories () {
return Api().get('/stories')
}
}
and in the view (components/Stories.vue):
<template>
<div class="stories">
<h1>Stories</h1>
<div v-if="stories" class="table-wrap">
<div v-for="story in stories" :key="story.id">
<h3>Title: {{story.title}}</h3>
<p>Summary: {{story.description}}</p>
</div>
</div>
<div v-else>
There are no stories... Let's add one now <br><br>
<!-- <router-link v-bind:to="{ name: 'NewStory' }" class="add_story_link">Add Story</router-link> -->
</div>
</div>
</template>
<script>
import StoriesService from '@/services/StoriesService'
export default {
data () {
return {
stories: []
}
},
mounted () {
this.getStories()
},
methods: {
async getStories () {
const response = await StoriesService.fetchStories()
this.stories = response.data.stories
}
}
}
</script>
In the Rails app, cors.rb is:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
methods: %i(get post put patch delete options head)
end
end
I made the suggested adjustment. here is the response from the GET request to the back end in the. It shows the data coming through, but for some reason, it does not display from the v-for loop.
Your Rails API endpoint is returning the stories array assigned to a data
property, eg
{
"data":[...]
}
The response body object is assigned to response.data
via Axios so what you actually want is
this.stories = response.data.data