【问题标题】:Posting data to REST API (coded in Ruby/Sinatra platform) using Jquery使用 Jquery 将数据发布到 REST API(在 Ruby/Sinatra 平台中编码)
【发布时间】:2013-12-06 01:34:36
【问题描述】:

我在 Ruby/Sinatra 平台上开发了一个简单的 REST API。当我通过 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 

运行 Ruby 代码的 cmd 中的消息

"OPTIONS/test HTTP/1.1" 404 445(当我通过 jquery 发帖时) "POST/test HTTP/1.1" 200 61(当我通过 REST 客户端浏览器扩展发布时)

两个请求之间的区别是 OPTIONS 和 POST。如何解决?

【问题讨论】:

    标签: jquery ruby rest rubygems sinatra


    【解决方案1】:

    您的问题似乎是跨域 POST。

    有不同的方法来解决它:

    jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox 使用 JSONP 回调

    jQuery.ajax sending both OPTIONS and POST, how to handle with Express.js (Node.js) OPTIONS 请求的响应

    该示例适用于 node.js,但您可以针对 sinatra 进行调整。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-10
      • 2020-11-06
      • 2015-10-08
      • 2016-08-19
      • 2015-08-12
      • 2020-12-07
      • 2013-06-21
      • 2018-07-24
      相关资源
      最近更新 更多