Reputation: 3607
So I have a remote server which is supposedly a REST API: a GET request to http://api/somehting
is returning a json response. REST API is written in python with flask so the construction of the response is
from flask import jsonify
return jsonify(status=200, response="TEST")
When I go to a browser and paste that link i get the response. When I use POSTMAN and send a GET request to that link obviously it works fine.
But here is the catch with javascript (typescript). I started writing an angular app and i have created a service which should get that data from the same link previously. The code for that looks like this:
getProducts(): Observable<IProduct[]> {
return this._http.get<IProduct[]>(this._productUrl).do(data => console.log(
"All: " + JSON.stringify(data))).catch(this.handleError);
}
Now when this function gets executed i get this error in the browser:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api/somehting. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
So my questions are:
1) Why i dont get an error on postman or web browser but i get on angular app? How do i fix this?
2) This is just a JSON response. I include all the information in json body. It is intended to give anyone a response who requests it. Why i am even getting this "The Same Origin Policy" error?
3) How to make that my API would act as any other public API where you send a request and get an answer back?
Upvotes: 0
Views: 1673
Reputation: 1158
Why i dont get an error on postman or web browser but i get on angular app? How do i fix this?
Postman doesn't care about same origin policies, this is something browsers implement. When making a direct call to your API through the URL bar, it has a similar behavior. So there isn't anything to fix, as it is working as intended.
This is just a JSON response. I include all the information in json body. It is intended to give anyone a response who requests it. Why i am even getting this "The Same Origin Policy" error?
This is a security measure browsers implement in order to protect users from malicious websites accessing other site's sensitive data (e.g. Facebook account, online banking, etc.). Browsers don't care what the content of the request is (JSON, XML, strings), it just knows that you are attempting to make an AJAX to a different domain. So it will trigger the same origin policy.
How to make that my API would act as any other public API where you send a request and get an answer back?
If you want a public API, you can add "Access-Control-Allow-Origin: *" to your response header from the server. That tells the browser that any domain can make a call to your server.
Upvotes: 4