javascript - ParseError while trying to handle a CORS request -


i trying make api call static page rails api. hosted on different domains need enable cors — can pre-flighted request or simple cors request.

the error getting actiondispatch::paramsparser::parseerror (399: unexpected token @ 'object object]'). have no idea how 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 similar one) did work older project , consistent gist. felt error in client code tried different methods:

script1.js:

            var url = "http://localhost:3000/v1/visitors/";             var method = "post";             var postdata = {email: email, phone: phno};              var async = true;              var request = new xmlhttprequest();             request.onload = function () {                 // can kinds of information http response.                 var status = request.status; // http response status, e.g., 200 "200 ok"                 var data = request.responsetext; // returned data, e.g., html document.                 console.log("response " + data);             };              request.open(method, url, async);              request.setrequestheader("content-type", "application/json;charset=utf-8");             request.setrequestheader("x-requested-with", "xmlhttprequest");             request.send(postdata); 

script2.js:

            $.ajax({                 url: 'http://localhost:3000/v1/visitors/',                 type: 'post',                 data: {email: email, phone: phno},                 crossdomain: true,                 datatype: "json",                 contenttype: 'application/json; charset=utf-8',                 headers: {"x-requested-with": "xmlhttprequest"},                 error: function (xhr) {                     console.log('error: ' + xhr.statustext);                 },                 success: function (result) {                     //                 },                 async: true,                 processdata: false             }); 

but in both cases same error:

xmlhttprequest cannot load http://localhost:3000/v1/visitors/. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:63342' therefore not allowed access. response had http status code 400.

error in server logs:

started post "/v1/visitors/" 127.0.0.1 @ 2016-02-08 17:49:43 +0530   activerecord::schemamigration load (0.1ms)  select "schema_migrations".* "schema_migrations" error occurred while parsing request parameters. contents:  [object object]  actiondispatch::paramsparser::parseerror (399: unexpected token @ 'object object]'):   actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:53:in `rescue in parse_formatted_parameters'   actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:32:in `parse_formatted_parameters'   actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:23:in `call'   activerecord (4.2.5) lib/active_record/query_cache.rb:36:in `call'   activerecord (4.2.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'   activerecord (4.2.5) lib/active_record/migration.rb:377:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'   activesupport (4.2.5) lib/active_support/callbacks.rb:88:in `__run_callbacks__'   activesupport (4.2.5) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'   activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks'   actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:27:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/reloader.rb:73:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'   railties (4.2.5) lib/rails/rack/logger.rb:38:in `call_app'   railties (4.2.5) lib/rails/rack/logger.rb:20:in `block in call'   activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `block in tagged'   activesupport (4.2.5) lib/active_support/tagged_logging.rb:26:in `tagged'   activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `tagged'   railties (4.2.5) lib/rails/rack/logger.rb:20:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/request_id.rb:21:in `call'   rack (1.6.4) lib/rack/runtime.rb:18:in `call'   activesupport (4.2.5) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'   rack (1.6.4) lib/rack/lock.rb:17:in `call'   actionpack (4.2.5) lib/action_dispatch/middleware/static.rb:116:in `call'   railties (4.2.5) lib/rails/engine.rb:518:in `call'   railties (4.2.5) lib/rails/application.rb:165:in `call'   rack (1.6.4) lib/rack/content_length.rb:15:in `call'   puma (2.16.0) lib/puma/server.rb:557:in `handle_request'   puma (2.16.0) lib/puma/server.rb:404:in `process_client'   puma (2.16.0) lib/puma/server.rb:270:in `block in run'   puma (2.16.0) lib/puma/thread_pool.rb:106:in `call'   puma (2.16.0) lib/puma/thread_pool.rb:106:in `block in spawn_thread'     rendered /home/vedant/.gem/ruby/2.2.4/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.5ms)   rendered /home/vedant/.gem/ruby/2.2.4/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.4ms)   rendered /home/vedant/.gem/ruby/2.2.4/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.6ms)   rendered /home/vedant/.gem/ruby/2.2.4/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (10.6ms) 

seems real noob error. sending incorrect json data. had change

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

to

postdata = json.stringify({email: email, phone: phno}); 

using client side script1.js works fine.

hope qna serves reference attempting cors call rails api.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -