2013-11-21 33 views
1

我在Ruby/Sinatra平臺中開發了一個簡單的REST API。當我通過REST客戶端,Firefox擴展發佈數據時,API工作正常。這裏是我的API使用Jquery將數據發佈到REST API(使用Ruby/Sinatra平臺編碼)

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 

從那裏我正在我的Ruby代碼

在CMD消息 「選項/測試HTTP/1.1」 404 445(當我通過jQuery的發佈) 「POST /測試HTTP/1.1」 200 61(當我通過REST客戶端瀏覽器擴展發佈時)

兩個請求之間的差異是OPTIONS和POST。如何解決它?

回答

相關問題