3
3

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.

【学習1日目】node.jsによる画面遷移

Last updated at Posted at 2018-09-23
sample.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(1234);

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

next.html
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title> sample </title>
</head>
<body>
<h1> 次のページ </h1>
<p> 最初のページを押して見てね! </p>
<a href ="/index"> 最初のページ へ </a>
</body>
</html>

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title> sample </title>
</head>
<body>
<h1> 初心者からの離脱 </h1>
<p> 次のページを押して見てね! </p>
<a href ="/next"> 次のページ へ </a>
</body>
</html>


・以下追記
sample.jsに無駄があったので修正。同じファイルをなんども読み込んでいた。

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

var indexPage = fs.readFileSync('./ index. html', 'utf-8');
var nextPage = fs.readFileSync('./ next. html', 'utf-8');



var server = http.createServer(function(req,res) {var target = '';
 switch (req.url){
   case '/':
   case '/index':
    target = indexPage;
     break;
   case '/next':
     target = nextPage;
     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(1234);

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


3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?