Ruby on rails 使用AngularJS访问API时,Rails请求内容类型似乎不正确
我有一个简单的Rails 4.1.4应用程序,我正在尝试将单独主机上的AngularJS应用程序连接到它的API。虽然我认为访问它没有问题,但Rails似乎认为请求是HTML,而忽略了内容类型:“application/json”Ruby on rails 使用AngularJS访问API时,Rails请求内容类型似乎不正确,ruby-on-rails,angularjs,doorkeeper,Ruby On Rails,Angularjs,Doorkeeper,我有一个简单的Rails 4.1.4应用程序,我正在尝试将单独主机上的AngularJS应用程序连接到它的API。虽然我认为访问它没有问题,但Rails似乎认为请求是HTML,而忽略了内容类型:“application/json” Started GET "/api/v1/locations?access_token=xxx&headers=%7B%22Content-type%22:%22application%2Fjson%22%7D" for 127.0.0.1 at 2014-0
Started GET "/api/v1/locations?access_token=xxx&headers=%7B%22Content-type%22:%22application%2Fjson%22%7D" for 127.0.0.1 at 2014-09-03 17:12:11 +0100
Processing by Api::V1::LocationsController#index as HTML
Parameters: {"access_token"=>"xxx", "headers"=>"{\"Content-type\":\"application/json\"}"}
在我的NG应用程序中,我尝试了多种标题组合,包括:
app.factory('Location', ['$resource', "$localStorage",
function($resource, $localStorage){
return $resource('http://my-api.com/api/v1/locations/', {headers:{'Content-type' : 'application/json'}}, {
query: {
method: 'GET',
headers: {'Content-type': 'application/json'},
isArray: true,
dataType: 'json',
params: { access_token: $localStorage.accessToken }
}...
NG端的响应看起来正常,尽管my locations controller中只有以下内容,但仍使用JSON进行响应:
class Api::V1::LocationsController < Api::V1::BaseController
doorkeeper_for :all
before_filter :authorize
respond_to :json
def index
@locations = @current_user.locations.order("created_at desc").limit(5)
respond_with @locations
end
end
class Api::V1::LocationsController
我还设置了(并测试了unset)cors头
我在某个地方读到,如果内容类型头中有正向斜杠,Rails将不会读取它
虽然这似乎不会引起很多问题,但我确实认为它会干扰作为应用程序一部分的门卫。这不是Rails的问题。原来我需要在NG配置中修改一些标题等 我在app.js中添加了以下内容
$httpProvider.defaults.useXDomain = true;
// $httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
第二行抛出了一个错误,但我留下了一个很好的度量。很抱歉,我没有提到主题,但您是如何使用api处理身份验证的?我们使用passport/express/node安全地进行身份验证,然后将访问令牌传递给Angular。只是浪费了一个小时试图解决这个问题。我很感激你发布这个!顺便说一句,这也修复了以rails作为后端的Restangular。