DEV Community

koki-takishita
koki-takishita

Posted on

2 2

vue サーバーからデータを取得して表示する

前提条件

  • バックエンドはRails
  • 自作のAPIサーバーからデータを取る
  • vue_cliで作成
  • パッケージ管理はnpm

一次情報

手順

  1. axiosインストール
  2. export default {}内にサーバーとやり取りするコードを記述
  3. Rails側設定

axiosインストール(HTTP通信ができるようになる)

  • pakage.jsonがあるディレクリに移動後下記のコマンド実行
$ npm install axios --save
Enter fullscreen mode Exit fullscreen mode

サーバーとやり取りするコードを記述

  • コンポーネントmethods内にaxiosのコード追記
-----------
  template
-----------

<script>
  import axios from [インストール先パス];

  export default {
  name: 'test',
  data: {
    test: []
  },
  methods{
    // メソッドreadが発火したら取りにいくという想定
    read(){
      axios
      .get('https://取得したいサーバドメイン名')
      .then((response) {

        // responseが実際に取得するデータ
        console.log(response);

        // responseの中のdata属性に取得したいデータが格納されている.
        // thisはvuecomponentオブジェクト 配列であるtestに格納している.
        // 取得するデータがJSONだとdataでいいっぽい APIそんな触らないから他のパターンもあるかも
        this.test = response.data;
      })
      .catch((error) {
        // handle error
        console.log(error);
      })
    },
  }
  };
</script>
Enter fullscreen mode Exit fullscreen mode
  • 長々と書いたが、実際に気にするのはどこから取得するかと、取得したデータの格納先 今回記述したコードはaxiosのサンプルコードとほぼ同じ.サンプルコードを下記に示す.
const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
Enter fullscreen mode Exit fullscreen mode

Rails側設定

  • CORS対策でRails側の設定が必要
gem 'rack-cors'
Enter fullscreen mode Exit fullscreen mode
  • config/initializers/cors.rbコメントアウトを有効に
# Be sure to restart your server when you modify this file.

# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.

# Read more: https://github.com/cyu/rack-cors

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://データを贈りたいパス'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
Enter fullscreen mode Exit fullscreen mode
  • 変更するのはoriginsの指定のみ

  • Railsサーバーを再起動させて、データをこれで取得できるはず.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More