我有一个Rails 5.2.2 API,该API在localhost:3000 / v1 / stories上提供JSON数据。我正在尝试设置一个Vuejs应用程序以将其与Axios一起使用。 rails终端显示请求,并且不抛出错误:
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 vue应用程序中,有以下相关文件:
Api.js检索基本连接:
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')
}
}
并在视图(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>
在Rails应用中,cors.rb是:
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
答案 0 :(得分:1)
您的Rails API端点正在返回分配给data
属性的 stories 数组,例如
{
"data":[...]
}
响应主体对象是通过Axios分配给response.data
的,所以您真正想要的是
this.stories = response.data.data