【问题标题】:How can I return a response to an AngularJS $http POST to Sinatra?如何将 AngularJS $http POST 的响应返回给 Sinatra?
【发布时间】:2014-10-10 03:29:16
【问题描述】:

我能够从 AngularJS 成功 POST 到我的 Sinatra 路由,这样我就获得了“200”状态。

当我在 Chrome 中检查时,我看到请求负载如下:

{"input":"testing"}

但是响应是空的。

我是这样发布的:

        $http({
        method: "POST",
        url: "http://floating-beyond-3787.herokuapp.com/angular",
        /*url: "https://worker-aws-us-east-1.iron.io/2/projects/542c8609827e3f0005000123/tasks/webhook?code_name=botweb&oauth=LOo5Nc0x0e2GJ838_nbKoheXqM0",*/
        data: {input: $scope.newChat}
    })

    .success(function (data)
    {
     // $scope.chats.push(data);
        $scope.chats.push($scope.newChat)
     // if successful then get the value from the cache? 

    })
    .error(function (data)
    {
      $scope.errors.push(data);
    });

  };

  $scope.newChat = null

请求有效负载下的 Chrome 显示正确 - 如上所述。

当我在运行 Sinatra 应用程序的 Heroku 中检查日志时,我无法判断我是否正确处理了请求负载。而且我肯定没有在响应中得到任何东西:

post '/angular' do
  puts "params: #{params}"
  puts params[:input]
  puts @json = JSON.parse(request.body.read)

   return RestClient.post 'https://worker.io' {:send => params[:input]}

end

我的期望是:

  1. Sinatra 应用可以接收负载:输入
  2. 它可以在 Iron.io 上成功发布给我的工作人员
  3. 它可以在对 Angular JS 的响应中返回一些内容以及 Success。

这可能吗?如果可以,怎么做?

【问题讨论】:

    标签: ruby angularjs heroku sinatra


    【解决方案1】:

    您可能会遇到这样一种情况,即 request.body 在到达您的路线之前已经被进一步阅读。

    试试下面的

    request.body.rewind
    request_payload = JSON.parse request.body.read
    

    这是在 Sinatra 中遇到的一个相当常见的问题,因此如果这解决了您的问题,您可能需要将其放在前置过滤器中。

    before do
      request.body.rewind
      @request_payload = JSON.parse request.body.read
    end
    

    以下内容也不适用于 JSON 有效负载。

    params[:input]
    

    如果 Content-Type 为 application/x-www-form-urlencoded,则 params[:field] 样式有效,以允许以传统 Web 应用程序样式访问表单数据。它还可以从参数化路由中提取参数;类似于以下内容。

    post '/angular/:data'
      puts params[:data]
    
      # Do whatever processing you need in here
      # assume you created a no_errors var to track problems with the
      # post
    
      if no_errors
        body(json({key: val, key2: val2, keyetc: valetc}))
        status 200
      else 
        body(({oh_snap: "An error has occurred!"}).to_json) # json(hash) or hash.to_json should both work here.
        status 400 # Replace with your appropriate 4XX error here... 
      end
    end
    

    我最近做的事情是使用最后一种样式post 'myroute/:myparam,然后在客户端对 JSON 有效负载进行 Base64 编码,并将其发送到 URL :myparam 槽中。这有点小技巧,我不建议将其作为一般做法。我有一个客户端应用程序无法将 JSON 数据 + 标头正确编码到请求正文中;所以这是一个可行的解决方法。

    【讨论】:

    • 谢谢,是的,我有 params[:input] 在那里,所以我可以实际测试问题是否在客户端。
    • 我的替代方法是直接发布到 worker.io,但 worker 以创建任务作为响应——但在工作完成后无法发回响应。
    • 收到有效负载后,有没有办法让我将工作人员返回给发布帖子的 AngularJS?
    • 澄清一下;您是在问是否可以在 post 路由完成时返回有效负载?
    • 是的。但只有在它接收到来自 POST'ing 到外部网络服务的有效负载之后。
    猜你喜欢
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多