了解Angular2中外部服务的CORS处理 [英] Understanding CORS handling for external service in Angular2

查看:81
本文介绍了了解Angular2中外部服务的CORS处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一种尝试从外部URL提取数据的情况('

案例2:ASP.NET MVC核心1.0,浏览器Chrome,IDE:VS社区2015

 公共IActionResult Index(){字符串GET_DATA_URL ="http://knowstack.com/webtech/charts_demo/data.json";HttpClient client1 =新的HttpClient();client1.BaseAddress =新的Uri(GET_DATA_URL);client1.DefaultRequestHeaders.Accept.Clear();client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));HttpResponseMessage response1 = client1.GetAsync(GET_DATA_URL).Result;如果(response1.IsSuccessStatusCode){var dataObjects = response1.Content.ReadAsStringAsync().Result;var rootObj = JsonConvert.DeserializeObject< dynamic>(dataObjects);}别的{//处理失败响应}返回View();} 

如果您需要我身边的任何信息,请告诉我.

解决方案

我猜想ASP.NET代码是在您的服务器上执行的,然后服务器将HTML返回给您.

CORS是浏览器中内置的一项技术.浏览器阻止网站对不允许外部访问的外部网站进行AJAX调用.因为对于ASP.NET,此请求由您的后端完成.因为对于后端,这是一个普通的HTTP请求(就像您对浏览器所做的一样),所以不需要检查CORS.因此,该请求也不会发送"origin"标头.CORS只是为了防止来自外部主机的AJAX呼叫.

您可以在Angular2中进行此操作,是在您的域上创建一个代理,该代理将绕过对外部服务的请求,并且就像请求发生在您的站点上一样,因此不需要CORS.

I came across one scenario where I am trying to fetch data from external URL ('http://knowstack.com/webtech/charts_demo/data.json')

In case of Angular2, I am getting CORS error. As per my understanding, CORS need to enable on service side and not in Angular2 application.

But I do not have access service side. Hence, this can’t be done.

Now, if I change my front end from Angular2 to ASP.NET MVC core UI and use httpClient class of System.Net.Http namespace. I do get a response and data back.

I am wondering how this is working in ASP.NET MVC core UI and Angular2 front-end gives me CORS error. How to overcome this external service CORS scenario in Angular2?

Below are my 2 cases along with code-

Case 1: Angular2

In this, I am using Angular2 version RC4 with npm version 3.9.6, node version 4.4.7. Browser chrome, Editor: VScode

To execute application, I am simply using ‘npm start’ command.

        this._http.get('http://knowstack.com/webtech/charts_demo/data.json')
                .map(this.extractData)
                .subscribe((response) => {
                    this.options11 = {
                                    title : { text : 'knowstack' },
                                    series : [{
                                        name : 'knowstack',
                                        data : response.json()
                                    }]
                                };
                },
                (error) => { 
                    this.errorMessage = <any>error
                });

Error in browser console:

Case 2: ASP.NET MVC core 1.0, Browser chrome, IDE: VS community 2015

    public IActionResult Index()
    {
           string GET_DATA_URL = "http://knowstack.com/webtech/charts_demo/data.json";

            HttpClient client1 = new HttpClient();
            client1.BaseAddress = new Uri(GET_DATA_URL);

            client1.DefaultRequestHeaders.Accept.Clear();
            client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response1 = client1.GetAsync(GET_DATA_URL).Result;

            if (response1.IsSuccessStatusCode)
            {
                var dataObjects = response1.Content.ReadAsStringAsync().Result;

                var rootObj = JsonConvert.DeserializeObject<dynamic>(dataObjects);

            }
            else
            {
                // handle failure response
            }
        return View();
    }

Please let me know if you need any information from my side.

解决方案

I guess the ASP.NET code is executed on your server and the server then returns the HTML to you.

CORS is a technology that is build into the browser. The browser prevents websites to make AJAX calls to foreign websites that don't allow access from outside. Because in the case of ASP.NET this request is done by your backend. Because for the backend this is a normal HTTP request (like you do with your browser) it doesn't need to check for CORS. Because of this the request also doesn't send the "origin" header. CORS is only there to prevent AJAX calls from foreign hosts.

What you can do to make this work in Angular2 is to create a proxy on your domain that just bypasses the request to the external service and acts like the request happens to your site so CORS isn't needed.

这篇关于了解Angular2中外部服务的CORS处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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