現在
https://sbfl.net/blog/2018/08/25/nodejs-express-webapi/
こちらのサイトを参考にNode.jsでexpressを使い、簡単なAPI作成を勉強中の初心者です。
やりたいことは、アプリをデプロイして、コマンドプロントでnode index.jsと起動するのと同じように起動したいです。
コードはサイトからのコピペです。
javacsript
1// expressモジュールを読み込む 2const express = require('express'); 3 4// expressアプリを生成する 5const app = express(); 6 7// webフォルダの中身を公開する 8app.use(express.static('web')); 9 10// http://localhost:3000/api/v1/list にアクセスしてきたときに 11// TODOリストを返す 12app.get('/api/v1/list', (req, res) => { 13 // クライアントに送るJSONデータ 14 const todoList = [ 15 { title: 'JavaScriptを勉強する', done: true }, 16 { title: 'Node.jsを勉強する', done: false }, 17 { title: 'Web APIを作る', done: false } 18 ]; 19 20 // JSONを送信する 21 res.json(todoList); 22}); 23 24// ポート3000でサーバを立てる 25app.listen(3000, () => console.log('Listening on port 3000'));
html
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <title>TODOリスト</title> 6 <style> 7 html { 8 background-color: rgb(240, 240, 240); 9 } 10 </style> 11</head> 12<body> 13 <h1>TODO List</h1> 14 <div> 15 <ul id="todo-container"></ul> 16 </div> 17 18 <script> 19 // APIからJSONを取得する 20 fetch('./api/v1/list') 21 .then((response) => response.json()) 22 .then((todoList) => { 23 // id="todo-container"要素を取得する 24 const todoContainer = document.querySelector('#todo-container'); 25 26 // コンテナの中身を全部消す 27 todoContainer.innerHTML = ''; 28 29 // JSONの各要素に対して 30 for(const item of todoList) { 31 const li = document.createElement('li'); // リスト要素 32 const label = document.createElement('label'); // ラベル 33 const checkbox = document.createElement('input'); // チェックボックス 34 checkbox.type = 'checkbox'; 35 checkbox.checked = item.done; // 項目がdoneならチェック 36 const text = new Text(item.title); // 項目名 37 38 // ラベルにチェックボックスとテキストを追加する 39 label.appendChild(checkbox); 40 label.appendChild(text); 41 42 // リスト要素に先ほどのラベルを追加する 43 li.appendChild(label); 44 45 // TODOリストにリスト要素を追加する 46 todoContainer.appendChild(li); 47 } 48 }) 49 </script> 50</body> 51</html>
フォルダ構成は以下の通りです。
プロジェクトフォルダ
|--node_modulesフォルダ
|--webフォルダ--index.html
|--index.js、package.json、package-lock.json
上記コードをnode index.jsで起動し、http://localhost:3000/にアクセスすると
index.jsがはたらいた状態でhtmlページが表示されます。
これをwebアプリとしてデプロイして同じように表示する方法を探しています。
デプロイ先として試したのは、AWS Amplify、Google firebase、heroku等ですが、
いずれもindex.jsの動かし方がわかりませんでした。
調べては試すの繰り返しなので、理解不足は承知の上ですが、ご教示頂ければ幸いです。
追記
そもそも上記フォルダ構成をそのままデプロイしようというのが間違いなのでしょうか?
expressプロジェクトには既定のフォルダ構成があるようですが、そのルールに従わないといけない気がしてきました。
そのあたりも含めてアドバイスを頂けるとありがたいです。
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。