Felix Schett
Felix Schett

Reputation: 25

Rails JSON Parameter not parsed

I have a registration form in ReactJS and want to to send the user data (name, email, password) in JSON format to my rails API. Rails then does not parse my JSON data into parameters.

Routes

Rails.application.routes.draw do
    get '/list_users' => 'users#index'
    post '/register_user' => 'users#register'
end

User Controller

class UsersController < ApplicationController
    def index
        @users = User.all
        render json: @users
    end

    def register
        puts params.inspect
        @user = User.new(name: 'TEST', :email => params[:email], :password => params[:password])
        #@user = User.new(name: 'User', email: '[email protected]', password: 'password') (this works)
        @user.save
    end
end

puts params.inspect outputs:

<ActionController::Parameters {"controller"=>"users", "action"=>"register"} permitted: false>

Registration form

postData(){
    var myHeaders = new Headers();
    myHeaders.append('Accept', 'application/json')
    myHeaders.append('Content-Type', 'application/json');

    var data = JSON.stringify({
        name: "Test",
        email: "[email protected]",
        password: "password"
    })

    fetch("http://127.0.0.1:3000/register_user",{
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: data
    })
    .then(function(res){ return res.json(); })
    .then(function(data){ alert( JSON.stringify( data ) ) })
    .catch( (ex) => {
        console.log("Fetch failed" + ex);
    });
}

parameter wrapping for JSON is enabled in the config. Thanks for the help!

Upvotes: 1

Views: 1207

Answers (2)

Felix Schett
Felix Schett

Reputation: 25

configuring Rack::Cors to accept OPTIONS did the trick, like sideshowbarker explainend in his comment.

application.rb

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

and in the frontend

mode: 'cors'

Upvotes: 1

omikes
omikes

Reputation: 8543

JSON parameters in this case will not have symbolic keys, but string ones. Try this instead:

@user = User.new(name: 'TEST', :email => params['email'], :password => params['password'])

Upvotes: 0

Related Questions