【问题标题】:How can I pass http header from JQuery to Rails via get request?如何通过 get 请求将 http 标头从 JQuery 传递到 Rails?
【发布时间】:2015-12-07 02:00:17
【问题描述】:

我想将标头从 jQuery ajax 方法传递给 Rails。这是我的要求:

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

这里是 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

如果没有标头,则此 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"):

如何将此标头传递给我的应用程序?

【问题讨论】:

    标签: jquery ruby-on-rails http ruby-on-rails-4 http-headers


    【解决方案1】:

    就这样吧:

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

    (默认方法是'GET')

    仅当您想更改标头X-Requested-With: XMLHttpRequest 的默认值时才使用beforeSend 函数,该标头始终发送。

    Reference

    【讨论】:

    • 我一开始试过这个,但是效果不好。
    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2018-11-29
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多