Reputation: 644
I am completely newbie in ruby, so I made a form with POST http method, but it fails as follows:
ruby sinatra_msg.rb
[2017-08-04 07:47:50] INFO WEBrick 1.3.1
[2017-08-04 07:47:50] INFO ruby 2.3.3 (2016-11-21) [x86_64-linux]
== Sinatra (v2.0.0) has taken the stage on 4567 for development with backup from WEBrick
[2017-08-04 07:47:50] INFO WEBrick::HTTPServer#start: pid=18141 port=4567
127.0.0.1 - - [04/Aug/2017:07:48:00 -0300] "GET / HTTP/1.1" 404 458 0.0083
127.0.0.1 - - [04/Aug/2017:07:48:00 -03] "GET / HTTP/1.1" 404 458
- -> /
I have the following file tree:
.
├── sinatra_msg.rb
└── views
├── index.erb
└── msg.erb
Content of sinatra_msg.rb: # coding: utf-8 require 'sinatra'
post '/' do
body = params[:body]
erb :index
end
post '/show-msg' do
msg = params[:msg]
text = params[:text]
erb :msg
end
Content of index.erb
<!DOCTYPE html>
<html>
<head></head>
<body>
<h2>Testing Sinatra post</h2>
<form action="/show-msg" method="POST">
subject: <input name="msg[subject]"> <br />
text: <input name="msg[text]"> <br />
<input type="submit">
</form>
</body>
</html>
This a content of msg.erb:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h2>Testing output</h2>
<h1>Hi!</h1>
<p>
<%= params['msg']['text'] %>
</p>
<a href='/'>Home</a>
</body>
</html>
What's wrong with this code? (Using ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-l])
I've replaced POST
by GET
only in the first section and it worked:
# coding: utf-8
require 'sinatra'
get '/' do
body = params[:body]
erb :index
end
post '/show-msg' do
msg = params[:msg]
text = params[:text]
erb :msg
end
I wonder if is that right, can I do only GET for '/' ?
Upvotes: 1
Views: 825
Reputation: 1519
The code is correct.
When you access a page in your browser, the browser sends a GET http method by default, you have to specify the POST when you want.
It is possible to POST to '/', there is no constraint on HTTP on which method can be applied to an url.
Upvotes: 1