Rails API 响应请求,但 axios 未检索数据

Rails API responding to request, but axios not retrieving data

我有一个 Rails 5.2.2 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)

我的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

我做了建议的调整。这是从 GET 请求到后端的响应。它显示通过的数据,但出于某种原因,它不显示来自 v-for 循环的数据。

您的 Rails API 端点正在返回分配给 data 属性 的 stories 数组,例如

{
  "data":[...]
}

响应主体对象通过 Axios 分配给 response.data 所以你真正想要的是

this.stories = response.data.data