8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsで画面遷移を行う

Posted at

Node.jsとは?

[初心者] Node.jsでHello Worldする
[初心者向け] [Node.js] fsモジュールを使ってhtmlファイルを返す

わからなければ↑の記事をご参考ください!!

画面遷移を行う

Node.jsでは、リクエスト(URL)ごとにレスポンスとして返却する内容を使い分けることにより、結果として画面遷移を実現させる

以下コード

server.js
var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, res) {
  var target = '';
  switch (req.url) {
    case '/':
    case '/index':
      target = './index.html';
      break;
    case '/next':
      target = './next.html';
      break;
    default:
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('bad request');
      return;
  }


  fs.readFile(target, 'utf-8', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  })
});

server.listen(3000);
console.log('サーバーを起動しました。');

適当にhtmlファイルを用意する

index.html
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>sample</title>
  </head>
  <body>
    <h1>Hello world</h1>
    <h2>This is First Page</h2>
    <a href="/next">To next page</a>
  </body>
</html>
next.html
<!DOCTYPE html>
<html lang="ja" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>sample</title>
  </head>
  <body>
    <h1>Hello world</h1>
    <h2>This is Next Page</h2>
    <a href="/next">To First page</a>
  </body>
</html>

解説

また今度書くので記事なる方はいいねしといていただけると通知が行きます!

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?