[英]Angular 2 Typescript - Enable CORS header ‘Access-Control-Allow-Origin’
I have Angular 2 typescript application running on my localhost. 我在本地主机上运行了Angular 2打字稿应用程序。 I have to access external REST API in my application.
我必须在应用程序中访问外部REST API。 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).
(原因:CORS标头“ Access-Control-Allow-Origin”缺失)。
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
我不认为这个包可以用于Angular 2 Typescript应用程序。它用于express.js
npm install cors --save
How do I set this CORS header 'Access-Control-Allow-Origin' using typescript for entire project/application? 如何为整个项目/应用程序使用打字稿设置此CORS标头“ Access-Control-Allow-Origin”? 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();
The server that hosts that API needs to enable CORS. 承载该API的服务器需要启用CORS。 This is a limitation of client-side languages - they make these REST requests through the browser.
这是客户端语言的限制-它们通过浏览器发出这些REST请求。 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. 对于服务器端语言,例如PHP甚至nodeJS / expressJS,这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.