前提
Express、Vue.js、HTMLで仮想通貨の値段を取得するアプリを作っています。
ExpressからbitflyerのpublicAPIを使ってデータは取得できたのですが、
HTML(Vueにデータを渡す)に反映させることができません。
初歩的な質問で申し訳ございませんが、ご教示いただければ幸いです。
実現したいこと
- 仮想通貨の名称(eth_jpy等)を入力しボタンを押したら、仮想通貨の値段が表示されること。
発生している問題・エラーメッセージ
取得した仮想通貨のデータ(以下コードのcryptValue)をHTML(Vueにデータを渡す)に反映させることができません。
該当のソースコード
Expres(Node.js)
1const express = require('express'); 2const path = require("path"); 3const app = express(); 4const request = require('request'); 5 6app.use(express.static(path.join(__dirname, "public"))) 7app.use(express.urlencoded({ extended: false })) 8 9 10app.get('/', (req, res) => { 11 res.render('public/index.html', { 12 cryptName: cryptName, 13 cryptValue: cryptValue 14 }) 15}); 16 17app.post('/', (req, res) => { 18 const cryptName = req.body.cryptName 19 20 let options = { 21 url: 'https://api.bitflyer.com/v1/getticker?product_code=' + cryptName, 22 method: 'GET', 23 json: true 24 }; 25 26 request(options, function (error, response, body) { 27 console.log(body); 28 cryptValue = JSON.stringify(body.best_bid) 29 res.redirect('/'); 30 }) 31}); 32app.listen(3000)
HTML
1<!DOCTYPE html> 2<html lang="ja"> 3 4<head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Document</title> 9 <link rel="stylesheet" href="css/styles.css" /> 10</head> 11 12<body> 13 <div id="app"> 14 <h2>仮想通貨アプリ</h2> 15 <form action="/" method="post"> 16 <p> 17 <input type="text" name="cryptName" placeholder="名称"> 18 <input type="text" v-model="cryptValue"> 19 <button v-on:click="cryptGet">更新</button> 20 </p> 21 <p>{{ cryptValue }}</p> 22 </form> 23 </div> 24 <script src="https://unpkg.com/vue@next"></script> 25 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 26 <script src="js/app.js"></script> 27</body> 28 29</html>
Vue.js
1const app = Vue.createApp({ 2 data: () => ({ 3 cryptValue: '' 4 }) 5}) 6 7app.mount('#app') 8
試したこと
Vueから直接外部APIの仮想通貨のデータを取得しようとしたら、CORSのエラーが出てしまいました。調べたところフロントサイドのVueでは無理なことがわかったので、Expressを使用してサーバーを経由して取得しようとしています。
補足情報(FW/ツールのバージョンなど)
Node.js:v18.7.0
あなたの回答
tips
プレビュー