使用Jquery将数据发布到RESTAPI(在Ruby/Sinatra平台中编码)

使用Jquery将数据发布到RESTAPI(在Ruby/Sinatra平台中编码),jquery,ruby,rest,rubygems,sinatra,Jquery,Ruby,Rest,Rubygems,Sinatra,我在Ruby/Sinatra平台上开发了一个简单的RESTAPI。当我通过REST客户端Firefox扩展发布数据时,API工作正常。这是我的API代码 require 'rubygems' require 'sinatra' require 'sinatra/json' require 'json' require 'sinatra/cross_origin' configure do enable :cross_origin end set :environment, :producti

我在Ruby/Sinatra平台上开发了一个简单的RESTAPI。当我通过REST客户端Firefox扩展发布数据时,API工作正常。这是我的API代码

require 'rubygems'
require 'sinatra'
require 'sinatra/json'
require 'json'
require 'sinatra/cross_origin'
configure do
  enable :cross_origin
end
set :environment, :production
post '/test' do
 cross_origin :allow_origin => '*',
    :allow_methods => [:post],
    :allow_credentials => true,
    :max_age => "60"
  data = JSON.parse(request.body.read)
  aFile = File.new("data/data.json", "w+")
if aFile
   aFile.syswrite(data)
end
  json data
end


get '/test' do
   cross_origin :allow_origin => '*',
    :allow_methods => [:get],
    :allow_credentials => true,
    :max_age => "60"
  aFile = File.new("data/data.json", "r+")
if aFile
  content = aFile.sysread(100)
end
  json content
end
此Ruby代码正在本地服务器上的端口4567上运行。现在,当我试图从jquery发布数据时,我得到了404错误。这是我的jquery代码

var prospect_id=5;
var customer_id=10;
var page=  window.location.pathname + window.location.search;
var dataString='{"prospect_id" : "'+prospect_id+'", "c_id" : "'+customer_id+'", "page" : "'+page+'"}';
var url = "http://localhost:4567/test";
$.ajax({  
       type: "POST",  
       url: url,  
       data:JSON.stringify(dataString),  
       success: function(msg){
                             var obj=JSON.parse(msg);
                            alert(obj);
                            }
            });
我在javascript控制台中遇到以下错误

 OPTIONS http://localhost:4567/test 404 (Not Found) jquery.min.js:29
    OPTIONS http://localhost:4567/test Invalid HTTP status code 404 jquery.min.js:29
    XMLHttpRequest cannot load http://localhost:4567/test. Invalid HTTP status code 404 
cmd中运行Ruby代码的地方的消息

选项/测试HTTP/1.1 404 445当我通过jquery发布时 POST/test HTTP/1.1 200 61当我通过REST客户端浏览器扩展发布时


两个请求之间的直接关系是OPTIONS和POST。如何修复它

看来您的问题是跨源POST

有不同的解决方法:

使用JSONP回调

对选项请求的响应

该示例适用于node.js,但您可以将其应用于sinatra