如何将头添加到ActiveResource以创建API请求

How to add headers to ActiveResource to create API request

本文关键字:创建 API 请求 ActiveResource 添加      更新时间:2023-09-26

我有一个rails应用程序,我需要连接到外部RESTful API(而不是另一个rail应用程序),我得到了在js中工作的基本get请求,如下所示:

<h1>JavaScript in Body</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
   var method = "GET";
   var url = "https://api.appery.io/rest/1/db/collections/Menu/";
   var header = "X-Appery-Database-Id: 5476a8c5e4b05e4a44a69b0e";
   var response = "response";
   var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader("X-Appery-Database-Id", "5476a8c5e4b05e4a44a69b0e");
   xhr.send(null);
   // subscribe to this event before you send your request.
   xhr.onreadystatechange = function() {
     if (xhr.readyState === 4 && xhr.status === 200) {
       response = xhr.responseText;
       document.getElementById("demo").innerHTML = response;
     }
   } 
}
</script>
</body>
</html> 

现在,我在rails应用程序中为我的项目提供了以下内容。rb

class Item < ActiveResource::Base
   self.site = "https://api.appery.io/rest/1/db/collections/Menu/"
end

在我的show.html.erb中,我有:

<% provide(:title, @user.name) %>
<% require 'active_resource' %>
<div class="row">
    <aside class="col-md-4">
    <section class="user_info">
        <h1>
            <% item = Item.all %>
            <%= item.first %>
        </h1>
        </section>
    </aside>
</div>

我得到以下错误:

失败。响应代码=400。响应消息=错误的请求。

这是有道理的,因为我还没有包括头球,但我不知道该怎么做。activeresource页面没有任何关于添加标题的示例,我不确定您是否可以只添加self.header = "my header here"。我应该使用activeresource还是应该使用restclient之类的东西,或者我可以使用我正在使用的javascript并将其添加到我的应用程序中?非常感谢您的帮助。

不确定您在这里到底在寻找什么。是否有理由从javascript调用API?如果你在控制器端有所有的信息,你可以使用RestClient进行一个简单的调用:

response = RestClient.post( 
  "https://api.appery.io/rest/1/db/collections/Menu/", 
  nil,
  :content_type => :json, :accept => :json, 
  :'X-Appery-Database-Id' => "5476a8c5e4b05e4a44a69b0e")

然后,您可以解析响应,并向视图发送它所需要的内容。