Add custom response header with Rack-cors and Grap

2019-09-12 06:58发布

问题:

I'm developing a Ionic(Cordova) app with a Ruby on Rails API. I want to use response headers to return a token after login. I'm using rack-cors gem to make Cross Origin Request work:

application.rb

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do
      allow do
        origins '*'
        resource '/api/*', :headers => :any, :methods => [:get, :post, :options, :put]
      end
    end

and grape gem to manage my API routes. But i can't find a way to add a header to my response since i added rack-cors.

I tried this:

header('Access-Token', user.token.key)

But it doesn't work. Whatever i do i end up with those headers:

{cache-control: "max-age=0, private, must-revalidate", content-type: "application/json"}

Can anyone help me with this issue ?

回答1:

I used gem 'devise_token_auth'

Also, i had this configuration in application.rb.

  class Application < Rails::Application
    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true

    config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*',
          :headers => :any,
          :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
          :methods => [:get, :post, :options, :delete, :put]
      end
    end

  end