Node.js はブラウザ上で動かしているわけではないので、 HTML は必要ありません。
let i = 1;
function display() {
console.log(i);
i++;
}
setInterval(display, 1000);
Node.js で HTML を配信してみましょう。
通常 express パッケージを用いるので、以下のコマンドを入力して、 express パッケージをインストールします。
// e-とぴあ の PC はプロキシがあるので、以下が必要です。
npm config set proxy http://proxy.e-topia-kagawa.local:8080/
npm config set https-proxy http://proxy.e-topia-kagawa.local:8080/
// 自宅や自分の PC を使用する際には、上記は必要ありません。
npm install express
var express = require("express");
const app = express();
//8080番ポートでサーバー
app.listen(8080, () => {
console.log("サーバー起動中");
});
app.get("/", (req, res) => {
res.send("<html>Hello!</html>");
res.end();
});
Node.js の中に HTML を埋め込んでいくのは大変なので、別に用意した HTML ファイルを配信してみましょう。
index.html
<html>
<body>
Hello, World!
</body>
</html>
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
別に用意した JS ファイルも配信してみましょう。
index.html
<script type="text/javascript" src="sample.js"></script>
sample.js
alert("Hello World!");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/sample.js", (req, res) => {
res.sendFile(__dirname + "/sample.js");
});
views/index.html
<html>
<body>
<p><%= name %>さん、こんにちは。</p>
</body>
</html>
npm install ejs
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', function (req, res) {
res.render("index", { name: "Tam" });
});
JS回で郵便番号をネットワークから取得すると、セキュリティエラーが出ていました。
以下のようにすると、エラーが出ずに取得できます。
app.get("/zip.csv", (req, res) => {
fetch("http://etp.xsrv.jp/reskilling/3/37KAGAWA_ZIP_UTF-8.csv")
.then((resp) => resp.text())
.then((text) => {
res.send(text);
res.end();
});
});
JS回で作成した郵便番号検索ツールを Node.js に対応させてみましょう。
$theme: gaia template: invert