我有一个 Rails 应用程序,需要连接到外部 RESTful API(不是另一个 Rails 应用程序),并且我收到了在 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 应用程序中的 item.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>
我收到以下错误:
Failed. Response code = 400. Response message = Bad Request.
这是有道理的,因为我没有包含标题,但我不知道该怎么做。 activeresource 页面没有任何有关添加 header 的示例,我不确定您是否可以这样做 self.header = "my header here"
。我应该使用activeresource还是应该使用restclient之类的东西,或者我可以只使用我正在使用的javascript并将其添加到我的应用程序中吗?非常感谢任何帮助。
最佳答案
不确定您到底在寻找什么。有什么理由从 javascript 进行 API 调用吗?如果您掌握了 Controller 端的所有信息,则可以使用 RestClient 进行简单的调用:
response = RestClient.post(
"https://api.appery.io/rest/1/db/collections/Menu/",
nil,
:content_type => :json, :accept => :json,
:'X-Appery-Database-Id' => "5476a8c5e4b05e4a44a69b0e")
然后您可以解析响应,并将其需要的内容发送到 View 。
关于javascript - 如何向 ActiveResource 添加 header 以创建 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28779721/