vedant1811 February 2016

ParseError while trying to handle a CORS request

I am trying to make an API call from my static page to my rails api. They are hosted on different domains so I need to enable CORS — it can be a pre-flighted request or a simple CORS request.

The error I am getting is ActionDispatch::ParamsParser::ParseError (399: unexpected token at 'object Object]'). I have no idea how this is happening.

My rails API code:

controller.rb:

class VisitorsController < ApplicationController

  skip_before_filter :verify_authenticity_token

  before_filter :set_headers
  after_filter :cors_set_access_control_headers

  def create
    puts 'VisitorsController#create'
    @visitor = Visitor.new(visitor_params)

    if @visitor.save
      render json: @visitor, status: :created
    else
      render json: @visitor.errors, status: :unprocessable_entity
    end
  end

private
  def visitor_params
    params.permit(:email, :phone)
  end

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
    headers['Access-Control-Max-Age'] = '1728000'
  end

  def set_headers
    puts 'set_headers'
    if request.method == 'OPTIONS'
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
      headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token, Content-Type'
      headers['Access-Control-Max-Age'] = '1728000'

      render :text => '', :content_type => 'text/plain'
    end
  end
end

routes.rb:

match 'visitors', to: 'visitors#create', via: [:options, :post]

The above setup (or a similar one) did work for an older project and it is also consistent with this

Answers


vedant1811 February 2016

Seems like it was a real noob error. I was sending incorrect json data. All I had to do was to change

postData = {email: email, phone: phno};

to

postData = JSON.stringify({email: email, phone: phno});

Using the client side script1.js everything works fine.

Hope this QnA serves as a reference for anyone attempting a CORS call to a rails api.

Post Status

Asked in February 2016
Viewed 2,826 times
Voted 6
Answered 1 times

Search




Leave an answer