gpt4 book ai didi

ruby-on-rails - 使用 AngularJS 访问 API 时,Rails 请求内容类型似乎不正确

转载 作者:行者123 更新时间:2023-12-01 19:34:11 25 4
gpt4 key购买 nike

我有一个简单的 Rails 4.1.4 应用程序,我正在尝试将单独主机上的 AngularJS 应用程序连接到它的 API。虽然我访问它没有问题,但 Rails 似乎认为请求是 HTML 并忽略 Content-Type: '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-09-03 17:12:11 +0100
Processing by Api::V1::LocationsController#index as HTML
Parameters: {"access_token"=>"xxx", "headers"=>"{\"Content-type\":\"application/json\"}"}

在我的 NG 应用程序中,我尝试了多种 header 组合,包括:

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 端看起来不错,它使用 JSON 进行响应,尽管我的位置 Controller 中只包含此内容:

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

我还设置(并测试取消设置)cors header 。

我在某处读到,如果内容类型 header 中有正斜杠,Rails 将不会读取内容类型 header ...

虽然这似乎不会引起很多问题,但我确实认为它会干扰作为应用程序一部分的 Doorkeeper。

最佳答案

这不是 Rails 问题。结果我需要在 NG 配置中摆弄一些 header 等。

我将以下内容添加到 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";

第二行抛出了一个错误,但我保留在那里以进行更好的测量。

关于ruby-on-rails - 使用 AngularJS 访问 API 时,Rails 请求内容类型似乎不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com