[英]How to add headers to ActiveResource to create API request
我有一個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>
我收到以下錯誤:
失敗。 響應代碼=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")
然后,您可以解析響應,並將其發送給視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.