如何创建跨域请求? [英] How to create cross-domain request?
问题描述
如何使用Angular 2创建跨域请求?
How to create a cross-domain request using Angular 2?
您能提供一个示例吗?
类似于localhost:3000之间的请求和localhost:8000跨域
Can you provide an example?
Like a request between localhost:3000 and localhost:8000 cross-domain
推荐答案
事实上,Angular2中没有任何关于跨域请求的事情。 CORS是浏览器原生支持的东西。此链接可以帮助您了解它的工作原理:
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:
- http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
- http://restlet.com/blog/2016/09/ 27 / how-to-fix-cors-problems /
- http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
- http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/
简而言之,在跨域请求的情况下,浏览器会自动在请求中添加 Origin
标头。有两种情况:
To be short, in the case of cross domain request, the browser automatically adds an Origin
header in the request. There are two cases:
- 简单请求。如果我们使用HTTP GET,HEAD和POST方法,则此用例适用。对于POST方法,仅支持具有以下值的内容类型:
text / plain
,application / x-www-form-urlencoded
和multipart / form-data
。 - 预检请求。当简单请求用例不适用时,会发出第一个请求(使用HTTP OPTIONS方法)来检查在跨域请求的上下文中可以执行的操作。
- 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
andmultipart/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.
因此实际上大多数工作必须在服务器端完成以返回CORS头。主要的一个是 Access-Control-Allow-Origin
一个。
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).
关于Angular2,只需使用 Http
对象与任何其他请求一样(例如,相同的域):
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(
...
);
这篇关于如何创建跨域请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!