Rails API应用程序抛出状态-1

时间:2016-12-05 02:00:17

标签: ruby-on-rails angularjs cors rack-cors

我有一个启用了CORS的Rails API应用程序。

但是,在我的前端角度代码中,当我点击同一个端点时,$ resource $ save函数不会执行成功回调。它从错误回调中的端点返回以下数据 -

{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"data":{"session":{"email":"shahravi@gmail.com","password":"foobar"}},"url":"http://localhost:3000/sessions.json","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":""}

我读到了那个状态" -1"表示CORS启用有问题。但我无法弄清楚会是什么。

为了启用CORS,我安装了' rack-cors' gem,并在我的rails application.rb

中有以下内容
class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true

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

    config.middleware.use ActionDispatch::Cookies
  end

我错过了启用CORS的内容吗?为什么我的rails应用程序返回status = -1?

更多的挖掘显示服务器正在发送正确的标头以响应请求,因此想知道此时可能出现的问题 -

>> curl -H "Origin:*" -I http://localhost:3000/users/1
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
ETag: W/"ec1e530cfc19612936b356773d26df36"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: c721b55a-148a-4b5b-8cd5-9fcb772477e7
X-Runtime: 0.022036
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, UPDATE, DELETE
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Vary: Origin

并且CORS似乎正确地插入到rails应用程序

>> bundle exec rake middleware
use Rack::Cors
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use ActionDispatch::Cookies
run Api::Application.routes

0 个答案:

没有答案