【问题标题】:Why can I make a REST API request from a browser but not from Angular's resource?为什么我可以从浏览器而不是 Angular 的资源发出 REST API 请求?
【发布时间】:2016-08-21 04:59:09
【问题描述】:

为什么我可以从浏览器/Postman/甚至 Node.js(http.get 方法)发出 REST API 请求,但不能从 Angular 资源发出?

错误信息的sn-p是:

XMLHttpRequest cannot load http://example-of-external-api-site.com 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.

在问这个之前,我试着看一下 CORS 的定义。根据我的理解,我可以理解为什么它不允许我从 Angular 的资源发出的请求,因为它来自不同的域。但是,我的浏览器/Postman/Node.js 应用程序不是也来自不同的域吗?

请帮我回答这个问题,我真的不明白为什么..

【问题讨论】:

    标签: angularjs cors


    【解决方案1】:

    当直接访问 url 时从浏览器发出请求时,您是在请求 url 的内容而不使用XMLHttpRequest

    $http.get()有两种情况:

    当访问与托管 AngularJS 内容的域不同的 uri 时,通过在浏览器呈现的内容中使用 XMLHttpRequest 的 ajax 调用,您必须提供与目标上的白名单匹配的 CORs 标头服务器。这是由于浏览器安全限制,以防止恶意攻击,例如跨站点脚本。

    当访问与托管 AngularJS 内容的域相同的 uri 时(通常通过相对路径完成:/Api/1 而不是 http://domain.com/api/1),不需要 COR 白名单,因为源和目标域是一样的。

    最后,当从节点调用 url 时,您正在进行服务器到服务器的并发调用,它没有相同的安全限制,因为它不在您的浏览器中执行。

    【讨论】:

    • 你能改写这段When accessing a uri via $http.get(), you are requesting resources from a domain other than that hosting your AngularJS content, via an ajax call utilizing XMLHttpRequest from within the rendered content of your browser. When you do this, you must provide a CORs header that matches the whitelisting on your server, per browser security restrictions.吗?我假设当我执行 $http.get 时,我正在从托管我的 AngularJS 内容的域中请求资源。
    • 根据您发布的错误消息,您的假设不正确。您通过XMLHttpRequest 请求http://example-of-external-api-site.com 的资源,因此出现了CORs 问题。如果您始终通过相对路径进行请求,则只能确保从托管您的内容的同一域请求资源。
    • 我通过 XMLHttpRequest 从我的域向 example-of-external-api-site.com 请求资源,了解 CORS 问题是如何存在的。我要澄清的是措辞from a domain other than that hosting your AngularJS content
    • 对不起,英语是我的第二语言,我想我明白你要解释的内容。
    • 没问题,如果我没有正确澄清,我深表歉意。请参阅我更新的答案。我已经扩展了我的 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2021-07-23
    • 1970-01-01
    • 2017-10-31
    • 2017-11-21
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多