node.jsのインストール
EC2のセキュリティグループの設定で3000番を開けておく
インストール
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
$ . ~/.nvm/nvm.sh
$ nvm install node
バージョン確認
$ node -e "console.log('Running Node.js ' + process.version)"
expressのインストール
npm init -y
npm i express -S
サーバーのファイルの記述し、実行する。
$ mkdir src
$ mkdir src/public
$ vi src/app.js
$ vi src/public/index.html
$ node src/app.js
src/app.js
// express モジュールのインスタンス作成
const express = require('express');
const app = express();
// パス指定用モジュール
const path = require('path');
// 3000番ポートで待ちうける
app.listen(3000, () => {
console.log('Running at Port 3000...');
});
// 静的ファイルのルーティング
app.use(express.static(path.join(__dirname, 'public')));
// その他のリクエストに対する404エラー
app.use((req, res) => {
res.sendStatus(404);
});
public/index.html
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>TEST</title>
<link rel="stylesheet" href="/css/sample.css">
</head>
<body>
<h1>Hello World!</h1>
<p id="hoge"></p>
<div>
<img src="/img/sample.png">
</div>
<script src="/js/sample.js"></script>
</body>
</html>