Reputation: 397
My question is familiar with: How should I format a JSON POST request to my rails app?
I am rookie in ruby on rails...just for 1 month study. I create a Rails with some easy funtions like CRUD. For now, i want to make some simple API for smartphone.
by use POSTMAN to test GET is OK. but POST always receive Status 422 Unprocessable Entity
what problems in my code... or does something i forget? thanks a lot...
The following are my codes.
controller:
def index
@users = User.all
render :json => @users
end
# GET /beacons/1
# GET /beacons/1.json
def show
@user = User.find(params[:id])
render :json => @user
end
def create
@user = User.new(user_params)
@user.save
respond_to do |format|
format.json { render :json => @user }
end
end
private
def user_params
params.require(:user).permit(:email, :password, :name)
end
routes:
namespace :api do
namespace :v1 do
resources :users, :defaults => { :format => :json }
end
end
use rake routes:
api_v1_users GET /api/v1/users(.:format) api/v1/users#index {:format=>:json} POST /api/v1/users(.:format) api/v1/users#create {:format=>:json}
my post:
{ "user": {"email": "2", "password": 2, "name": "2" } }
url:
http://localhost:3000/api/v1/users
Upvotes: 1
Views: 144
Reputation: 1234
It could be an issue with CSRF token, in application_controller.rb
, try replacing
protect_from_forgery with: :exception
with
protect_from_forgery with: :null_session
Also if possible post your question with the error log from rails s
Upvotes: 1