こちらの動画を見ながら、ローカルのUbuntu上でNode.jsアプリを作ってみました。
【最短30分でできる!】Node.js入門: 初心者でも簡単! ブラウザだけでNode.jsを使ったWeb開発!
開発環境
■OS
Ubuntu 18.04 Desktop
■Node.jsのバージョン
v12.16.0
プロジェクトの初期化
$ mkdir myapp $ cd myapp $ npm init 〜 質問事項には、とりあえず全部Enter 〜
Expressのインストール
$ npm install epress --save
最初のプログラム
myapp/server.js
const express = require('express'); // Expressモジュールの読み込み const app = express(); // URLトップ(/)にアクセスしたときの処理 app.get('/', (req, res) => { res.send('Hello, Node.js'); }); // 3000番ポートでウェブサーバーを立ち上げる app.listen(3000, () => { console.log('My app listening on 3000 port.'); });
ToDoアプリの作成
mongooseのインストール
$ npm install mongoose --save
server.jsを以下の内容に変更する。
静的ファイルの作成
appの下にpublicディレクトリを作成する。
$ mkdir public
index.htmlの作成。
<!DOCTYPE html> <html> <head> <title>Todo List</title> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="client.js"></script> </head> <body> <div class="container"> <h1>Task List</h1> <div class="form-group"> <input type="text" name="name" class="new-todo-text form-control" placeholder="task"> <button type="submit" class="btn btn-default" onclick="createTodo()">Add</button> </div> <h2>Current Tasks</h2> <table class="table table-striped task-table"> <thead> <th>Task</th><th> </th> </thead> <tbody class="todos"> <tr class="todo template" style="display: none;"> <td> <span class="text"></span> <span class="id" style="display:none;"></span> </td> <td> <button onclick="deleteTodo(this)">Delete</button> </td> </tr> </tbody> </table> </div> </body> </html>
クライアント側のJavaScriptファイルの作成。
function render(todos) { $(".todos").children().not(".template").remove(); const template = $(".todos").children(".template"); todos.forEach((todo) => { const node = template.clone(true).show().removeClass("template"); node.find(".text").text(todo.text); node.find(".id").text(todo._id); $(".todos").append(node); }); } function getTodos() { fetch('/api/todos') .then((data) => data.json()) .then((json) => { const todos = json; console.log(todos); render(todos); }); } function createTodo() { const text = $(".new-todo-text").val(); fetch("/api/todos", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({text: text}), }) .then(() => { getTodos(); }); } function deleteTodo(el) { const id = $(el).closest(".todo").find(".id").text(); fetch(`/api/todos/${id}`, { method: 'DELETE', }) .then(() => { getTodos(); }); } $(getTodos);
プログラムの実行
myappディレクトリに入り、以下のコマンドを実行する。
$ node server.js My app listening on port 3000.
ブラウザでhttp://localhost:3000にアクセスする。