0
0

More than 1 year has passed since last update.

WEBrickを使って静的なhtmlを返す

Last updated at Posted at 2021-10-06

WEBrickを使ってHTMLを返すというのを学習したので、アウトプットしようと思います。

http://localhost:8000/fom.htmlにアクセスして以下の画面が表示されるようにする

Image from Gyazo


(1)まずWEBrickというライブラリを使ってWebサーバーを構築する

webrick.rbファイルを作成し以下のコードを記述

webrick.rb
require 'webrick'

server = WEBrick::HTTPServer.new({ 
  :DocumentRoot => './',
  :BindAddress => '127.0.0.1',
  :Port => 8000
})  
解説

require 'ライブラリ' :外部ライブラリを読み込むメソッド

server = WEBrick::HTTPServer.new():newメソッドでWEBrick::HTTPServerクラスからインスタンスを作り、返り値をserverに代入する。

:DocumentRoot => './', :アクセス先はhttp~~/

:BindAddress => '127.0.0.1' :127.0.0.1は自分のパソコンにアクセスできる特別なipアドレス

:Port => 8000 :ポート番号8000番

(2)次にHTMLの作成

WEBrickはデフォルトで同一ディレクトリにあるindex.htmlファイルをレスポンスとして返す。なのでwebrick.rbファイルがあるディレクトリにform.htmlディレクトリを作り、そこにindex.htmlを入れる。

これでhttp://localhost:8000/fom.htmlにアクセスしたときにindex.htmlが返ってくる

form.html/index.htmlに以下を記述

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h2>GETで送る</h2>
  <ul>
  <form action="/form_get" method="get">  
    <li><label for="user_name">ユーザー名</label>
    <input type="text" name="user_name"></li>

    <li><label for="age">年齢</label>
    <input type="text" name="age"></li> 

  <button type="submit">投稿</button>
</form>
  </ul>


  <h2>POSTで送る</h2>
  <ul>
  <form action="/form_post" method="post">  
    <li><label for="user_name">ユーザー名</label>
    <input type="text" name="user_name"></li>

    <li><label for="age">年齢</label>
    <input type="text" name="age"></li> 

  <button type="submit">投稿</button>
</form>
  </ul>
</body>
</html>

解説

  • action 属性は、フォームで収集したデータを送信すべき場所 (URL) を定義します
  • method 属性は、データを送信するために使用する HTTP メソッド ( get または post ) を定義します
  • name 属性は、送るデータの名前(サーバーはその名前で受け取る)
  •  value属性は、入力された値が入る

これは、単なる静的なページを返している(HTMLの限界)

次回Rubyを使って投稿者ごとに異なるページを返すプログラムを作る(動的ページの作成)

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