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

但是,在我的前端角度代码中,当我点击相同的 endpoints 时,$ resource $ save函数不执行成功回调 . 它在错误回调中从 endpoints 获取以下数据 -

{"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