[英]How do you use a simple REST API’s with JavaScript
How do you get data from a REST API with JavaScript. 如何使用JavaScript从REST API获取数据。 I have several basic API's that I would like to get data from that don't require any authentication.
我有几个基本的API,它们不需要任何身份验证即可从中获取数据。 All of the API's return the data I want back in JSON.
所有API都以JSON返回我想要的数据。 For example https://www.codewars.com/api/v1/users/MrAutoIt .
例如https://www.codewars.com/api/v1/users/MrAutoIt 。 I thought this would be a very simple process using xmlhttprequest but it appears the same-origin policy is giving me problems.
我以为这是使用xmlhttprequest的非常简单的过程,但是似乎同源策略给我带来了问题。
I have tried following several tutorials but they don't seem to work on cross domains or I don't understand them. 我尝试了以下几篇教程,但它们似乎不适用于跨域,或者我听不懂。 I tried to post links to the tutorials but I don't have a high enough reputation on here yet.
我试图发布教程的链接,但是我在这里还没有很高的声誉。
If you are trying to access a web service that is not on the same host:port as the webpage that is issuing the request, you will bump into the same origin policy. 如果您尝试访问与发出请求的网页不在同一host:port上的Web服务,则将遇到相同的原始策略。 There are several things you can do, but all of them require the owner of the service to do things for you.
您可以做几件事,但是所有这些都需要服务的所有者为您做事。
1) Since same origin policy does not impact scripts, allow the service to respond by JSONP instead of JSON; 1)由于相同的来源策略不会影响脚本,因此允许服务通过JSONP而不是JSON进行响应; or
要么
2) Send Access-Control-Allow-Origin
header in the web service response that grants your webpage access 2)在授予您的网页访问权限的网络服务响应中发送
Access-Control-Allow-Origin
标头
If you cannot get the service owner to grant you access, you can make a request serverside (eg from Node.js or PHP or Rails code) from a server that is under your control, then forward the data to your web page. 如果你不能得到服务所有者向您授予权限,你可以做一个服务器端的请求(例如,从Node.js的或者PHP或者Rails代码)从那是你控制的服务器,然后将数据转发到您的网页。 However, depending on terms of service of the web service, you may be in breach, and you risk them banning your server.
但是,根据Web服务的服务条款,您可能会违反协议,并且冒使他们禁止您的服务器的风险。
In fact, it depends on what your server REST API supports regarding JSONP or CORS. 实际上,这取决于您的服务器REST API支持的JSONP或CORS。 You also need to understand how CORS works because there are two different cases:
您还需要了解CORS的工作原理,因为有两种不同的情况:
GET
, HEAD
and POST
. GET
, HEAD
和POST
。 In the case of POST
method, only content types with following values are supported: text/plain
, application/x-www-form-urlencoded
, multipart/form-data
. POST
方法,仅支持具有以下值的内容类型: text/plain
, application/x-www-form-urlencoded
, multipart/form-data
。 OPTIONS
) is done to check what can be done in the context of cross-domain requests. OPTIONS
)以检查在跨域请求的上下文中可以执行的操作。 That said, you need to add something into your AJAX requests to enable CORS support on the server side. 也就是说,您需要在AJAX请求中添加一些内容,以在服务器端启用CORS支持。 I think about headers like
Origin
, Access-Control-Request-Headers
and Access-Control-Request-Method
. 我考虑过
Origin
, Access-Control-Request-Headers
和Access-Control-Request-Method
。
Most of JS libraries / frameworks like Angular support such approach. 像Angular这样的大多数JS库/框架都支持这种方法。
With jQuery (see http://api.jquery.com/jquery.ajax/ ). 使用jQuery(请参阅http://api.jquery.com/jquery.ajax/ )。 There are some possible configurations at this level through
crossDomain
and xhrFields
> withCredentials
. 通过
crossDomain
和xhrFields
> withCredentials
可以在此级别进行一些配置。
With Angular (see How to enable CORS in AngularJs ): 使用Angular (请参阅如何在AngularJs中启用CORS ):
angular .module('mapManagerApp', [ (...) ] .config(['$httpProvider', function($httpProvider) { delete $httpProvider.defaults.headers.common['X-Requested-With']; });
If you want to use low-level JS API for AJAX, you need to consider several things: 如果要对AJAX使用低级JS API,则需要考虑以下几点:
XMLHttpRequest
in Firefox 3.5+, Safari 4+ & Chrome and XDomainRequest
object in IE8+ XMLHttpRequest
和IE8 +中的XDomainRequest
对象 xhr.withCredentials
to true
, if you want to use credentials with AJAX and CORS. xhr.withCredentials
为true
。 Here are some links that could help you: 以下是一些可以帮助您的链接:
Hop it helps you, Thierry Thierry,希望它对您有帮助
Here is how you get data. 这是获取数据的方式。
var request = new XMLHttpRequest();
request.open('GET', 'https://www.codewars.com/api/v1/users/MrAutoIt', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = this.response; // Success! this is your data.
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
As far as running into same origin policy... You should be requesting from an origin you control, or you can try disabling Chrome's web security, or installing an extension such as Allow-Control-Allow-Origin * to force headers. 至于遇到相同的来源策略...您应该从您控制的来源请求,或者您可以尝试禁用Chrome的网络安全性,或者安装诸如Allow-Control-Allow-Origin *的扩展名来强制标头。
For a get method you could have something like this: 对于get方法,您可以具有以下内容:
@section scripts{
<script type="text/javascript">
$(function()
{
$.getJSON('/api/contact', function(contactsJsonPayload)
{
$(contactsJsonPayload).each(function(i, item)
{
$('#contacts').append('<li>' + item.Name + '</li>');
});
});
});
</script>
}
In this tutorial check the topic: Exercise 3: Consume the Web API from an HTML Client 在本教程中,请检查主题: 练习3:从HTML客户端使用Web API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.