やってみたかったVue.jsでtwitterを作成できるものをアドバイスをいただき,できたので記事化です!!
完成
環境
実装した内容
基本的にNode.js のtwitterをからVue.js側にデータを渡しています
サーバー側
- npm initでprojectの作成
- express.js,twitter.js.axios.jsのinstall
- コードの作成
index.js
const express = require("express") const server = express(); // https://qiita.com/itagakishintaro/items/265e4910a777b08a787c var twitter = require('./twitter'); const allowCrossDomain = function (req, res, next) { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') res.header( 'Access-Control-Allow-Headers', 'Content-Type, Authorization, access_token' ) // intercept OPTIONS method if ('OPTIONS' === req.method) { res.send(200) } else { next() } } server.use(allowCrossDomain) server.get("/", function (req, res, next) { console.log("server is up"); res.send("server is up") }); server.get("/twitter", function (req, res, next) { twitter.timeline(req, function (result) { res.send(result); } ); }) server.listen(3000, function () { console.log('Listening on port 3000') });
twitter.js
var Twitter = require('twitter'); var client = new Twitter({ consumer_key: API_KEY, consumer_secret: API_KEY_SECRET, access_token_key: ACCESS_TOKEN, access_token_secret: ACCESS_TOKEN_SECRET, }); // タイムラインの取得 function timeline(urlInfo, callback) { var options = {}; if (urlInfo.query.screen_name) { options.screen_name = urlInfo.query.screen_name } client.get('statuses/user_timeline', options, function (error, tweets,response) { callback(tweets); }); } module.exports = { timeline:timeline }
フロント側
api.js
const axios = require("axios") const url_Base = "http://localhost:3000" const url_get = "/twitter" export function getApi(screen_name, callback) { axios .get(url_Base + url_get, { params: { screen_name:screen_name } }) .then(res => { console.log("res", res) callback(res.data) }) .catch(err => { console.log("err", err) callback(null) }) }
TwitterTest.vue
<template> <div> <input class="ui input" v-model="screen_name"> <button class="ui button" @click="apiTest(screen_name)">click to test twiter </button> <div class="ui centered cards" v-for="(item,index) in data" v-bind:key="index"> <div class="fluid card"> <div class="header">名前:{{item.user.screen_name}}</div> <div class="content"> {{item.text}} </div> <div class="content"> ツイート時間:{{item.created_at}} </div> </div> </div> </div> </template> <script> import { getApi } from '@/api/api.js' export default { data() { return { data: null, screen_name:'twitter' } }, methods: { apiTest(screen_name) { console.log('apiTest') getApi(screen_name, data => { this.data = data }) } } } </script>