简体   繁体   English

如何在JavaScript中使用简单的REST API

[英]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的工作原理,因为有两种不同的情况:

  • Simple requests . 简单的要求 We are in this case if we use HTTP methods GET , HEAD and POST . 在这种情况下,如果我们使用HTTP方法GETHEADPOST 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/plainapplication/x-www-form-urlencodedmultipart/form-data
  • Preflighted requests . 事前要求 When you aren't in the case of simple requests, a first request (with HTTP method OPTIONS ) is done to check what can be done in the context of cross-domain requests. 当您不是简单请求时,将执行第一个请求(使用HTTP方法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 . 我考虑过OriginAccess-Control-Request-HeadersAccess-Control-Request-Method

Most of JS libraries / frameworks like Angular support such approach. 像Angular这样的大多数JS库/框架都支持这种方法。

If you want to use low-level JS API for AJAX, you need to consider several things: 如果要对AJAX使用低级JS API,则需要考虑以下几点:

  • use XMLHttpRequest in Firefox 3.5+, Safari 4+ & Chrome and XDomainRequest object in IE8+ 在Firefox 3.5 +,Safari 4+和Chrome中使用XMLHttpRequest和IE8 +中的XDomainRequest对象
  • use xhr.withCredentials to true , if you want to use credentials with AJAX and CORS. 如果要对AJAX和CORS使用凭据,请使用xhr.withCredentialstrue

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.

相关问题 您如何使用WP REST API以简单的Javascript显示搜索结果? - How do you use the WP REST API to display search results in plain Javascript? 如何使用 JavaScript 的 forEach 来修改数组的内容? - How do you use JavaScript's forEach to modify the contents of an array? 您如何使用JavaScript处理附加的HTML ID? - How do you use javascript to handle appended HTML ID's? 如何在 javascript 中进行简单的 REST API 调用? 未捕获的 ReferenceError:未定义要求 - How to do simple REST API calls in javascript? Uncaught ReferenceError: require is not defined 如何仅使用Javascript对Marketo进行REST API调用? - How do you make a REST API call to Marketo using ONLY Javascript? 您如何知道Facebook Javascript API中的回调传递了什么? - How do you know what's passed into the callbacks in Facebook's Javascript API? 您如何在Javascript函数式编程中做一个简单的计数器? - How do you do a simple counter in Javascript functional programming? 没有Firebase库的情况下,如何在嵌入式JavaScript中使用REST API? - How do I use REST API in embedded JavaScript without a Firebase Library? 如何使用Javascript从网页导入简单数据 - How do you import simple data from a webpage using Javascript 如何在 javascript 中删除带有扩展和 rest 的嵌套属性 - How do you remove a nested property with spread and rest in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM