尝试处理 CORS 请求时出现 ParseError
Posted
技术标签:
【中文标题】尝试处理 CORS 请求时出现 ParseError【英文标题】:ParseError while trying to handle a CORS request 【发布时间】:2016-05-18 03:22:09 【问题描述】:我正在尝试从我的静态页面向我的 rails api 进行 API 调用。它们托管在不同的域上,因此我需要启用 CORS——它可以是预发送请求或简单的 CORS 请求。
我得到的错误是ActionDispatch::ParamsParser::ParseError (399: unexpected token at 'object Object]')
。我不知道这是怎么回事。
我的 Rails API 代码:
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]
上述设置(或类似设置)确实适用于较旧的项目,并且与 gist 一致。我觉得错误出在客户端代码中,所以我尝试了不同的方法:
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 ()
// You can get all kinds of information about the HTTP response.
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an 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)
// do something
,
async: true,
processData: false
);
但在这两种情况下,我都会遇到相同的错误:
XMLHttpRequest 无法加载 http://localhost:3000/v1/visitors/。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:63342” 使用权。响应的 HTTP 状态代码为 400。
服务器日志错误:
Started POST "/v1/visitors/" for 127.0.0.1 at 2016-02-08 17:49:43 +0530
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Error occurred while parsing request parameters.
Contents:
[object Object]
ActionDispatch::ParamsParser::ParseError (399: unexpected token at '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)
【问题讨论】:
解析错误很可能是由于您没有在数据上使用JSON.stringify
。只需将您的 ajax 请求更改为 data: JSON.stringify( email: email, phone: phone )
@BartJedrocha 您的评论和我的回答符合竞争条件——两者同时发生:D
哦哇刚刚看到了!很高兴你能够弄清楚并让它工作。干杯!
【参考方案1】:
似乎这是一个真正的菜鸟错误。我发送了不正确的 json 数据。我所要做的就是改变
postData = email: email, phone: phno;
到
postData = JSON.stringify(email: email, phone: phno);
使用客户端 script1.js
一切正常。
希望此 QnA 可为任何尝试对 rails api 进行 CORS 调用的人提供参考。
【讨论】:
以上是关于尝试处理 CORS 请求时出现 ParseError的主要内容,如果未能解决你的问题,请参考以下文章
发出 POST 请求时出现 Google Cloud Function CORS 错误
向 ASP.NET Web API 发送请求时出现 CORS 错误
从 ExtJS 向 node.js 请求时出现 CORS 问题。请求或响应标头不正确?
发出 GET 请求时没有 CORS 错误,但发出 POST 请求时出现 CORS 错误