Javascript 为什么对Rails API的GET请求不起作用?
我正在使用以下代码Javascript 为什么对Rails API的GET请求不起作用?,javascript,ruby-on-rails,api,get,typeahead.js,Javascript,Ruby On Rails,Api,Get,Typeahead.js,我正在使用以下代码获取所有机场数据(localhost:3000/api/v1/airports),以便自动完成机场信息 $(document).on('ready page:load', function () { var airports = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search_string'), queryTokenizer: B
获取所有机场数据(localhost:3000/api/v1/airports
),以便自动完成机场信息
$(document).on('ready page:load', function () {
var airports = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('search_string'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: window.location.origin + "/api/v1/airports"
}
});
// kicks off the loading/processing of `local` and `prefetch`
airports.initialize();
// passing in `null` for the `options` arguments will result in the default
// options being used
$('.typeahead').typeahead(null, {
name: 'airports',
displayKey: 'search_string',
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
source: airports.ttAdapter()
});
});
当我将其部署到Heroku并访问表单页面时,Chrome中的控制台将返回以下信息:
GET http://localhost:3000/api/v1/airports.json net::ERR_EMPTY_RESPONSE application-b3c93a17005e4f5b078b985c7fa12088.js:3
它应响应以下控制器:
module Api
module V1
class AirportsController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json
def index
respond_with(Airport.all)
end
def search
respond_with(Airport.pluck(:search_string))
end
def show
respond_with(Airport.find(params[:id]))
end
def create
@airport = Airport.new(airport.params)
if @airport.save
respond_to do |format|
format.json { render :json => @airport }
end
end
end
def update
@airport = Airport.find(params[:id])
if @airport.update(todo_params)
respond_to do |format|
format.json { render :json => @airport }
end
end
end
def destroy
respond_with Airport.destroy(params[:id])
end
end
end
end
它在我的开发环境中确实有效。有什么想法吗?您的资产,特别是您的javascript,包含指向http://localhost:3000
对于GET/json请求,我从javascript代码中的一些测试中猜测
它被编译并保留在那里
在生产环境中,对资产所做的更改不适用于已编译的资产(它们已编译…)
编译资产的唯一目的是更快地加载
因此,在每次更改之后,您必须重新编译资产以使更改生效。这是一个乏味的过程(我重复一遍,仅在标准的生产环境中),但如果您在生产环境中运行一个仍在开发中的应用程序,这是必要的(它的发生频率比您想象的要高)
这就是重新编译资产和重新启动应用程序服务器可以解决问题的原因。向我们展示您希望响应的控制器,以及应该匹配的路由。Heroku上的localhost????我不这么认为…@TamerShlash我已经用信息更新了这个问题。当我在本地运行代码时,它正在工作。@RubyRacer Simple copy paste。localhost:3000
不应该在那里。应该有Heroku部署的相应主机名。。。。您是否在代码中的任何位置硬编码了localhost
?也许可以清除浏览器缓存?
namespace :api, defaults: {format: :json} do
namespace :v1 do
get 'airports/search', to: 'airports#search', as: 'search'
resources :airports, :airlines, :countries
end
end