' P '

whatever I will forget

Node.js でサーバーの応答にてhtmlを表示させる方法

下記コードをindex.jsに記述する.

'use strict';
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/html; charset=utf-8'
  });
  res.write(
    '<!DOCTYPE html><html lang="ja"><body><h1>Displaying HTML/h1></body></html>'
  );
  res.end();
});
const port = 8000;
server.listen(port, () => {
  console.log('Listening on ' + port);
});

重要な部分

  • 'Content-Type': 'text/html; charset=utf-8' とする
  • res.write()に直接記述する
  • もしくはletなどで変数を作成し、HTMLをセットする
let html =  '<!DOCTYPE html><html lang="ja"><body><h1>Displaying HTML/h1></body></html>';
res.write(html);
  • 普通に行う場合は、fs.readFile()にてhtmlファイルを読み込んで、res.write()にセットするっぽい。