I'm trying to send custom headers to rails api, but I keep getting this stupid options!
ActionController::RoutingError (No route matches [OPTIONS] "/api/v1/surveys")
I've enabled headers I want to send in APIs application_controller.rb
, at least I think I did, by having the following code in it:
before_filter :allow_cross_domain
private
def allow_cross_domain
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-User-Token, X-User-Email, Origin, Content-Type, Accept, Authorization, Token'
end
And I'm trying to send X-User-Token
and X-User-Email
headers.
So on my client side I make the following call:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-type': 'application/x-www-form-urlencoded',
'X-User-Email': 'my@email.com',
'X-User-Token': 'fj4402SDgsGDS42'
},
url: Host.address + '/api/v1/surveys',
type: 'GET',
}).done(function(response){});
And I've also tried beforeSend
:
$.ajax({
url: Host.address + '/api/v1/surveys',
type: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('Accept','application/json');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-User-Email', 'my@email.com');
xhr.setRequestHeader('X-User-Token', 'fj4402SDgsGDS42');
},
}).done(function(response){}
It only breaks if I send X-User-Email
or X-User-Token
. When I send Accept
and Content-type
headers only, it works as it's suppose to.
Does anybody have any idea what might be causing this issue?
EDIT:
I haven't mentioned I'm using Devise for user authentication.
Adding the routes for survey
(I guess you don't need all of them :)
Rails.application.routes.draw do
devise_for :users, skip: [:registration, :sessions]
namespace :api, as: false do
namespace :v1, as: false do
resources :responses, only: [:index, :new, :create]
resources :surveys, only: [:index, :create, :show]
end
end
end
surveys GET /api/v1/surveys(.:format) api/v1/surveys#index
POST /api/v1/surveys(.:format) api/v1/surveys#create
survey GET /api/v1/surveys/:id(.:format) api/v1/surveys#show
Error I get in browser console is:
OPTIONS http://localhost:3003/api/v1/surveys
XMLHttpRequest cannot load http://localhost:3003/api/v1/surveys. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.