I am new to ruby on rails. I apologize early if this question might be dumb... but I can't figure this out and the tutorials I've seen is making this simple task confusing. Or I am just not understanding what I am missing or what to do... if a step by step tutorial may help, thanks!
My task to make a rails api that you can pass JSON to via postman/DH. The payload will be {"value": "foo"}. A '200 (OK)' Response with payload of {"value":"bar"}
No database needed, just a controller that takes in a payload and gives back a response.
This is what I do know...
$ gem install rails
$ rails new my_app --api
Add gem 'rack-cors'
at the bottom of your $RAILS_ROOT/Gemfile
( $RAILS_ROOT
stands for the root directory of your rails app), then
$ bundle install
Then add these lines to your $RAILS_ROOT/config/application.rb
, inside the class definition
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :patch, :put, :delete, :options]
end
end
$ rails g controller foo
Add an action to the FooController
(in file $RAILS_ROOT/controllers/foo_controller.rb
)
def create
foo = params[:foo]
# Do whatever you want with foo
render json: {value: 'bar'}
end
Modify the file $RAILS_ROOT/config/routes.rb
, add
post '/foo' => 'foo#index'
in the block
$ rails s
That's all. Now you can send POST requests to http://localhost:3000/foo
and see what happens.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.