Node.js リクエスト処理

ルーティング

const http = require(‘http’);
const fs = require(‘fs’);
const ejs = require(‘ejs’);
const url = require(‘url’);

var server = http.createServer(setResponse);
server.listen(3000);

function setResponse(request, response){

 const page = fs.readFileSync(‘./index.ejs’, ‘utf8’);
 const css = fs.readFileSync(‘./style.css’, ‘utf8’);

 URLをパース
 let url_parts = url.parse(request.url);
 
 URL判定
 switch (url_parts.pathname){
  case ‘/’:
   let content = ejs.render(page, {
    title: ‘Node.js’,
    message: ‘JavaScript’,
   });
   response.writeHead(200, {‘Content-Type’: ‘text/html’});
   response.write(content);
   response.end();
   break;
  case ‘/style.css’:
   response.writeHead(200, {‘Content-Type’: ‘text/css’});
   response.write(css);
   response.end();
   break;
  default:
   response.writeHead(200, {‘Content-Type’: ‘text/plain’});
   response.write(‘no page…’);
   response.end();
   break;
 }
}

GETパラメータ取得

var server = http.createServer(setResponse);
server.listen(3000);

function setResponse(request, response){

 クエリパラメータを含めてURLをパース
 let url_parts = url.parse(request.url, true);
 
 クエリパラメータ取得
 let query = url_parts.query;

 console.log(query);
 http://localhost:3000/?title=aaa&message=bbbb
 [Object: null prototype] { title: ‘aaa’, message: ‘bbbb’ }

 let content = ejs.render(page, {
  title: query.title,
  message: query.message,
 });
 response.writeHead(200, {‘Content-Type’: ‘text/html’});
 response.write(content);
 response.end();
}

POSTパラメータ取得

クライアント

<html lang=”ja”>
<body>
 <form method=”POST” action=”/post“>
  <input type=”text” name=”message“>
  <input type=”submit”>
 </form>
</body>
</html>

サーバ

const querystring = require(‘querystring’);

var server = http.createServer(setResponse);
server.listen(3000);

function setResponse(request, response){

 const page = fs.readFileSync(‘./index.ejs’, ‘utf8’);

 let url_parts = url.parse(request.url, true);
 switch (url_parts.pathname){
  case ‘/’:
   ~
   break;
  case ‘/post’:
   if (request.method == ‘POST’){
    let body = ”;
    リクエストデータ取得イベント(複数回発生する)    
    request.on(‘data’, (data) => {
     body += data;
    });
    リクエストデータ終了イベント
    request.on(‘end’, () => {     
     let postData = querystring.parse(body);
     console.log(body);
     message: ‘node.js’
     console.log(postData);
     [Object: null prototype] { message: ‘node.js’ }
     let content = ejs.render(page, {
      message: `POSTデータ:${postData.message}`,
     });
     response.writeHead(200, {‘Content-Type’: ‘text/html’});
     response.write(content);
     response.end();
    });
   }
   break;
  default:
   ~
 }
}