简体   繁体   English

如何通过get请求将JHeader中的http标头传递给Rails?

[英]How can I pass http header from JQuery to Rails via get request?

I would like to pass header from jQuery ajax method to Rails. 我想将标题从jQuery ajax方法传递给Rails。 This is my request: 这是我的要求:

$.ajax({ url: "http://localhost:3000/v1/examples", method: "GET", beforeSend: function(xhr){xhr.setRequestHeader('AuthenticationKey', 'some_key');}, dataType: "json" })

And here is routes.rb: 这是routes.rb:

Rails.application.routes.draw do
  namespace :v1, defaults: { format: :json } do
    devise_for :users, controllers: { sessions: "v1/sessions", registrations: "v1/registrations" }
    get 'examples', to:'examples#index'
  end
end

This get route for examples works if there is no header, but when I set custom header it doesn't. 如果没有标题,则此示例的get路由有效,但是当我设置自定义标题时,则无效。

Started OPTIONS "/v1/examples" for 127.0.0.1 at 2015-09-10 18:52:47 +0200
ActionController::RoutingError (No route matches [OPTIONS] "/v1/examples"):

How can I pass this header to my application? 如何将此标头传递给我的应用程序?

Just do it like this: 像这样做:

$.ajax({ 
    url: "http://localhost:3000/v1/examples", 
    headers: {'AuthenticationKey': 'some_key'},
    dataType: "json"
})

(default method is 'GET') (默认方法是'GET')

Use the beforeSend function only if you want to change the default value for the header X-Requested-With: XMLHttpRequest , which is always sent. 仅当要更改始终发送的标头X-Requested-With: XMLHttpRequest的默认值时,才使用beforeSend函数。

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM