簡體   English   中英

為什么此Sinatra API從此純JavaScript POST請求中獲取空的響應主體

[英]Why is this Sinatra API getting an empty response body from this pure JavaScript POST request

錫納特拉的路線:

post '/favorite' do
  response['Access-Control-Allow-Origin'] = '*'
  p response
end

JS:

注意:這還不是全部,而是相關內容。 它省略了創建喜歡的電影的方式,但是我保證在控制台日志中它會返回預期的效果,如下所述

window.onload = function(){
  var myApp = new App;
  myApp.addEventListenerToFavoriteButton();
};

var App = function(){
  this.myMovies = null
};

App.prototype.addEventListenerToFavoriteButton = function(){
  var self = this;
  document.querySelector('body').addEventListener('click', function(event) {
    if (event.target.tagName.toLowerCase() === 'button'){
      self.favorite(event.target.id);
    }
  });
};

App.prototype.favorite = function(movieID){
  var favoritedMovie = this.myMovies.movies[movieID]
  console.log(JSON.stringify(favoritedMovie)) // {title":"Yo soy Betty la fea","year":"1999–2001","imdbID":"tt0233127","html":"<h2>Yo soy Betty, la fea</h2><h3>1999–2001</h3><br><button id='0'>favorite</button>"}
  var url = "http://localhost:4567/favorite";
  var xhr = new XMLHttpRequest();
  xhr.open('POST', encodeURI(url), true);
  xhr.setRequestHeader("content-type",'application/json');
  xhr.onload = function() {
      if (xhr.status === 200 ) {
          console.log('tentative success!' + xhr.responseText); // tentative success!
      }
      else if (xhr.status !== 200) {
          alert('Request failed.  Returned status of ' + xhr.status);
      }
  };
  xhr.send(JSON.stringify(favoritedMovie));
}

var Movie = function(movieObject, index){
   this.title = movieObject['Title'],
   this.year = movieObject['Year'],
   this.imdbID = movieObject['imdbID']
   this.html = "<h2>" + this.title + "</h2><h3>" + this.year + "</h3><br><button id='" + index + "'>favorite</button>"
}

Sinatra控制台中的響應:

= Sinatra (v1.4.6) has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.5.0 codename Knife)
>> Maximum connections set to 1024
>> Listening on localhost:4567, CTRL+C to stop
#<Sinatra::Response:0x007f803b9061c8 @status=200, @header={"Content-Type"=>nil, "Access-Control-Allow-Origin"=>"*"}, @chunked=false, @writer=#<Proc:0x007f803b905ea8@/Users/awhit012/.rvm/gems/ruby-2.1.2/gems/rack-1.6.4/lib/rack/response.rb:30 (lambda)>, @block=nil, @length=0, @body=[]>
127.0.0.1 - - [07/Sep/2015:17:34:17 -0700] "POST /favorite HTTP/1.1" 200 - 0.0102

我嘗試添加

content_type :json

到路線。 這有一個區別:

@header={"Content-Type"=>"application/json", "Access-Control-Allow-Origin"=>"*"}

這對我來說似乎更好,但身體仍然是空的。

感謝user846250! 這個問題使Sinatra :: Request與Sinatra :: Response和Sinatra :: Headers混淆

post '/favorite' do
  headers 'Access-Control-Allow-Origin' => '*'
  p request
end

做到了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM