我在使用一个非常基本的网络应用程序时遇到了麻烦。这是我的文件:
公共/index.html
<!DOCTYPE html>
<html lang="en" data-ng-app>
<body>
<div data-ng-controller="PlayersCtrl">
<div data-ng-repeat="player in players">
{{player.id}}
</div>
</div>
<script src="/angular.min.js"></script>
<script src="/players.js"></script>
</body>
</html>
公共/players.js
function PlayersCtrl($scope, $http) {
$scope.players = [];
$http({
method: 'GET',
url: 'http://localhost:9292/hi'
}).success(function(data) {
$scope.players = data;
});
}
客户端.rb
require 'sinatra'
get '/' do
headers 'Access-Control-Allow-Origin' => '*'
headers 'Access-Control-Allow-Headers' => 'Authorization,Accepts,Content-Type,X-CSRF-Token,X-Requested-With'
headers 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS'
send_file File.join(settings.public_folder, 'index.html')
end
api.rb
require 'sinatra'
require 'json'
get '/hi' do
headers 'Access-Control-Allow-Origin' => '*'
headers 'Access-Control-Allow-Headers' => 'Authorization,Accepts,Content-Type,X-CSRF-Token,X-Requested-With'
headers 'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS'
[id: 1, name: "Bob"].to_json
end
对我来说,这似乎很好。然后,我启动服务器:
启动 api.rb
$ ruby api.rb -p 9292
[2013-03-07 23:57:43] INFO WEBrick 1.3.1
[2013-03-07 23:57:43] INFO ruby 2.0.0 (2013-02-24) [x86_64-darwin12.2.0]
== Sinatra/1.3.5 has taken the stage on 9292 for development with backup from WEBrick
[2013-03-07 23:57:43] INFO WEBrick::HTTPServer#start: pid=62634 port=9292
启动客户端.rb
$ ruby client.rb
[2013-03-07 23:57:40] INFO WEBrick 1.3.1
[2013-03-07 23:57:40] INFO ruby 2.0.0 (2013-02-24) [x86_64-darwin12.2.0]
== Sinatra/1.3.5 has taken the stage on 4567 for development with backup from WEBrick
[2013-03-07 23:57:40] INFO WEBrick::HTTPServer#start: pid=62610 port=4567
但是当我在本地主机(端口 4567)上使用浏览器时,我有以下日志:
api.rb 日志
127.0.0.1 - - [07/Mar/2013 23:57:46] "OPTIONS /hi HTTP/1.1" 404 442 0.0015
localhost - - [07/Mar/2013:23:57:46 CET] "OPTIONS /hi HTTP/1.1" 404 442
http://localhost:4567/ -> /hi
client.rb 日志
127.0.0.1 - - [07/Mar/2013 23:57:46] "GET / HTTP/1.1" 304 - 0.0093
localhost - - [07/Mar/2013:23:57:46 CET] "GET / HTTP/1.1" 304 0
- -> /
我做了很多关于跨域资源共享的搜索,并测试了许多不同的方法。我目前不知道如何处理。感谢您的任何帮助。
编辑:
我的问题是,api.rb 服务器error 404
在 AngularJS 调用之后返回一个。而且,有两个OPTIONS /hi
请求,这很奇怪。我认为这是 CORS 症状,但我添加了一些标题以接受跨域查询。
取而代之的是,服务器应返回200
带有 JSON 的 a。我真的不知道如何解决它。