如何创建跨域请求(Angular 2)? [英] How to create cross-domain request (Angular 2)?

查看:2608
本文介绍了如何创建跨域请求(Angular 2)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Angular 2创建跨域请求?
你能提供一个例子吗?
localhost:3000和localhost:8000之间的请求跨域?
谢谢。

解决方案

事实上,Angular2中没有关于跨域请求的事情。 CORS是浏览器本身支持的东西。此链接可以帮助您了解其工作原理:





简而言之,在跨域请求的情况下,浏览器会自动在请求中添加一个 Origin 头。有两种情况:




  • 简单请求。如果我们使用HTTP GET,HEAD和POST方法,则适用此用例。在POST方法的情况下,只支持具有以下值的内容类型: text / plain application / x-www-form-urlencoded multipart / form-data

  • 预发请求。当简单请求用例不适用时,会发出第一个请求(使用HTTP OPTIONS方法),以检查跨域请求上下文中可以执行的操作。



    • 因此,实际上大多数工作必须在服务器端完成以返回CORS头。主要是 Access-Control-Allow-Origin

        200 OK HTTP / 1.1 
      (...)
      Access-Control-Allow-Origin:*

      要调试此类问题,您可以在浏览器(网络标签)中使用开发人员工具。



      对于Angular2,只需使用 Http 对象与任何其他请求(例如相同的域):

       返回this.http。 get('https://angular2.apispark.net/v1/companies/')
      .map(res =&res; res.json())。subscribe(
      ...
      );


      How to create cross-domain request using Angular 2? Can you provide an example? Request between localhost:3000 and localhost:8000 cross-domain? Thank you.

      解决方案

      In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

      To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

      • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
      • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

      So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

      200 OK HTTP/1.1
      (...)
      Access-Control-Allow-Origin: *
      

      To debug such issues, you can use developer tools within browsers (Network tab).

      Regarding Angular2, simply use the Http object like any other requests (same domain for example):

      return this.http.get('https://angular2.apispark.net/v1/companies/')
                 .map(res => res.json()).subscribe(
        ...
      );
      

      这篇关于如何创建跨域请求(Angular 2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆