14
22

More than 3 years have passed since last update.

Vue.jsでSPA - [6] サーバからのデータ取得

Last updated at Posted at 2018-08-05

取得方法を調べる

JSでのサーバからのデータ取得方法はいくつか種類がかあるみたい.ざっと調べただけで以下

  1. XHR XMLHttpRequest : 昔ながらの方法でローレベルを書く感じ
  2. fetch API : 比較的新しい.Chromeでいうとversion 42かららしい
  3. Ajaxライブラリを使う : jQuery, superagent, axiosなどあげるとキリがない感じ

Vueの推奨は?

公式サイトでは、まあ、なんでもいいけどaxiosでどう?っていう感じの書き方 .vue-resourceのリタイアに関する記事で2016年なので少しふるいかもだが.

What Should I Use Then?
You are free to pick whatever you prefer (even just $.ajax), but as a default recommendation — particularly for new users — we suggest taking a look at Axios. It’s currently one of the most popular HTTP client library and covers almost everything vue-resource provides with a very similar API. In addition, it is universal, supports cancellation, and has TypeScript definitions.

それぞれ触ってみる

コマンドラインでさっとやりたかったのでnodeつかう(あとで逆にめんどくさいことに気づく)

XHR

事前にaxiosパッケージたしておく.

const axios = require('axios');

let url = 'https://api-staging.megaport.com/v2/locations'

axios.get(url)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

fetch

事前にnode-fetchパッケージたしておく.fetchの返り値はPromiseオブジェクト

var fetch = require("node-fetch");

let url = 'your-api-end-point-here';

fetch(url).then((response) => {
  //console.log(response.status);
  console.log(response);
}).catch(() => {
  console.log("error caught!");
});

Hack Your Design! によるとこっちのawaitを使う書き方がよりモダンとのこと

var fetch = require("node-fetch");

let url = 'your-api-end-point-here';

(async() => {
  try {
    const response = await fetch(url);
    //console.log(response.status);
    console.log(response);
  } catch (e) {
    console.log("error!")
  }
})();

axios

const axios = require('axios');

let url = 'your-api-end-point-here'

axios.get(url)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

nodeでやらなくても,Chrome DevToolsconsoleに上記をはりつければ動くし,そのほうがnodeの準備いらないので簡単だったのかぁ

ハマったところ

fetchPromiseを返してくるのだが,この場合にどうやってdataにアクセスするのかがよくわからず小ハマり.ひとまずresponseをJSONにしてみる.

fetch(url).then((response) => {
    console.log(response.json()); // to JSON
}).catch(() => {
    console.log("error!");
});

ここでPromiseの返す値をVueでdata配列にほりこもうとすると以下のようにおこられる.

[Vue warn]: Invalid prop: type check failed for prop "data". Expected Array, got Promise.

Promiseの中身を確認すると以下のようになっていてdata[[PromiseValue]]の下に配列としてある.ドット表記ではアクセスできない.

image.png

アクセス方法はstack overfowで見つけた.thenを使う.

fetch(url)
    .then(response => response.json())
    .then(data => console.log(data)) // then で data にアクセス
    .catch(error => console.error(error))

参考にしたサイト

次回

サーバからの値とれたので,でいよいよVueの中でつかっていくでぇ

シリーズ

14
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
22