LoginSignup
3

More than 5 years have passed since last update.

Github の草を取得して自分のサービスに表示する

Last updated at Posted at 2018-01-30

概要

こちらの記事で失敗したのでリベンジ。

どんな感じになる?

スクリーンショット 2018-01-30 9.41.28.png

ソースコード

vue ファイルは以下

App.vue
<template>
  <div>
    <input type="text" v-model="msg" >
    <button @click="getGarden()">get the garden!</button>
    <p v-if="msg.length > 0 && svg.length > 0">
      user: {{msg}}
      <br/>
      <span v-html="svg"></span>
    </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'longtime1116',
      svg: '',
    };
  },
  methods: {
    getGarden() {
      const XHR = new XMLHttpRequest();
      const query = `http://localhost:8081/getGarden.php?url=https://github.com/users/${this.msg}/contributions`;
      XHR.open('GET', query, true);
      XHR.onreadystatechange = (() => {
        if (XHR.status === 200) {
          this.svg = XHR.responseText;
        }
      });
      XHR.send(null);
    },
  },
};
</script>

以下の php を、php -S localhost:8081 で起動しておきます。

getGarden.php
<?php
//$data = file_get_contents("https://github.com/users/longtime1116/contributions");
$data = file_get_contents($_GET['url']);
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/plain");
print $data;

解説

vue.js 側

axios や fetch で php サーバからの応答を取得すると、ReadableStream 型で response が返ってきて処理が面倒くさいので、XMLHttpRequest を使いました。
(なんでXMLHttoRequestならうまくいくのかいまいちよくわかっていない。。。Promise形式だとReadableStreamを使うようになっている?)

また、取得した文字列を javascript 側で SVG として展開するために、テンプレート構文を使っています。

PHP側

CORS対策として、間に1枚PHPサーバをかませるようにしています。
PHP の方でAccess-Control-Allow-Originを付与しているのがそれです。

その他メモ

変数名に改善の余地あり。
URL そのままではなく user_name だけ php に渡すようにした方がいい。

Github リポジトリ

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
3