Reputation: 1967
I have Angular 2 typescript application running on my localhost. I have to access external REST API in my application. Whenever I try to access, I get this error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ***. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
What is the best solution to fix this issue. I dont want to use any plugin/addOns. I dont think so this package would work for Angular 2 Typescript application.It is used for express.js
npm install cors --save
How do I set this CORS header ‘Access-Control-Allow-Origin’ using typescript for entire project/application? Where do I need to add this header in below code?
var request = new XMLHttpRequest();
let myurl='http://remoteIP/api';
request.open('GET', myurl, true);
request.responseType = 'blob';
request.onload = function() {
var reader = new FileReader();
reader.readAsDataURL(request.response);
reader.onload = (e) => {
console.log('DataURL:', reader.result);
};
};
request.send();
Upvotes: 2
Views: 8257
Reputation: 537
The server that hosts that API needs to enable CORS. This is a limitation of client-side languages - they make these REST requests through the browser. The browser will change whatever mocked origin headers you give it to your actual website's headers.
This isn't an issue with server-side languages, such as PHP or even nodeJS/expressJS.
Upvotes: 2