kelvien
kelvien

Reputation: 347

Why can I make a REST API request from a browser but not from Angular's resource?

Why can I make a REST API request from a browser/Postman/ even Node.js (http.get method), but not from Angular resource?

The snippet of the error message is:

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.

Before asking this, I tried to look at the definition of CORS. And from my understanding, I can understand why it disallow the request I make from Angular's resource since it is coming from a different domain. But, isn't my browser/Postman/Node.js app are from a different domain as well?

Please help me answering this, I can't really understand why..

Upvotes: 4

Views: 2761

Answers (1)

David L
David L

Reputation: 33833

When a request is made from the browser when accessing a url directly, you are requesting the content of a url without the use of XMLHttpRequest.

There are two scenarios for $http.get():

When accessing a uri that is NOT the same domain that is hosting your AngularJS content, via an ajax call utilizing XMLHttpRequest from within the rendered content of your browser, you must provide a CORs header that matches the whitelisting on the target server. This is due to browser security restrictions to prevent nasty, malicious attacks such as Cross Site Scripting.

When accessing a uri that IS the same domain as that which is hosting your AngularJS content (typically done via relative paths: /Api/1 instead of http://domain.com/api/1), CORs whitelisting is not required, since both the origin and the target domain are the same.

Finally, when invoking a url from node, you are making a server to server concurrent call which does not have the same security restrictions since it is not executing within your browser.

Upvotes: 2

Related Questions