为什么这个Sinatra API从这个纯JavaScript POST请求中得到一个空的响应体

为什么这个Sinatra API从这个纯JavaScript POST请求中得到一个空的响应体,javascript,xml,api,post,sinatra,Javascript,Xml,Api,Post,Sinatra,西纳特拉的路线: post '/favorite' do response['Access-Control-Allow-Origin'] = '*' p response end JS: 注意:这不是全部,而是相关的位。它忽略了喜爱的电影是如何创建的,但我保证,当我将其记录在控制台日志中时,它将返回预期的结果,如下所述 window.onload = function(){ var myApp = new App; myApp.addEventListenerToFavorit

西纳特拉的路线:

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>"
}
到路线上去。这有一个区别:

@header={"Content-Type"=>"application/json", "Access-Control-Allow-Origin"=>"*"}
这对我来说似乎更好,但身体还是空的

感谢用户846250! 问题是将Sinatra::Request与Sinatra::Response和Sinatra::Header混淆

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

成功了

我在网上的某个地方找到了你的源代码?JS:Sinatra:源代码与你在这里发布的代码不一致,所以有点混乱。你的问题也令人困惑。我认为您将
Sinatra::Request
Sinatra::Response
混淆了。
Sinatra::Request
对象包含Javascript代码中由您的
xhr
对象发送的查询,
Sinatra::Response
对象是您将发送回Javascript代码的路径(并将由
xhr.onload
接收)。噢,我的上帝,谢谢您。我把那两个人搞糊涂了。抱歉,这让人困惑。那是因为我感到困惑。好好想想。我今天晚些时候会把解决方案贴出来。
@header={"Content-Type"=>"application/json", "Access-Control-Allow-Origin"=>"*"}
post '/favorite' do
  headers 'Access-Control-Allow-Origin' => '*'
  p request
end