Angular 2를 사용하여 응용 프로그램의 프런트 엔드를 만들고 XMLHttpRequest를 사용하여 제 3 자 사이트에서 이미지를로드하려고합니다.XMLHttpRequest의 오류 - "No '요청한 리소스에 Access-Control-Allow-Origin'헤더가 있습니다."
loadFile(fileUrl) {
const promise = new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', fileUrl, true);
request.setRequestHeader('Accept', 'image/jpeg');
request.onload =() => {
if (request.status === 200) {
resolve(request);
}
else {
reject(Error(request.statusText));
}
};
request.onerror =() => {
reject(Error('Network error.'));
};
request.send();
});
return promise;
}
그리고 이것은 내가 그것을 테스트하기 위해 사용하고있는 코드입니다 :
내 코드는 다음과 같습니다 나는 인터넷을 중심으로 검토 한 여러 페이지 내가해야했다
import FileHelper from './file-helper';
describe('File Helper',() => {
it('should retrieve the contents of an image on the web', (done) => {
let fileLoadPromise, fileContent;
fileLoadPromise = FileHelper.loadFile('http://adsoftheworld.com/files/steve-jobs.jpg');
fileLoadPromise.then((request: XMLHttpRequest) => {
fileContent = request.responseText;
expect(request.responseType).toEqual('image/jpeg');
done();
}).catch(error => {
console.log(error);
done.fail();
});
expect(fileContent).toBeTruthy();
});
});
내 머리글에 image/jpeg
을 추가하십시오. 따라서이 코드를 실행할 때마다 다음과 같은 오류 메시지가 나타납니다.
XMLHttpRequest cannot load http://adsoftheworld.com/files/steve-jobs.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9876' is therefore not allowed access.
아무도 도와 줄 수 있습니까?
'페이지에 스크립트는 응답의 내용을 읽을 수의 응답에'액세스 제어 - 허용 - Origin' 헤더를 제공해야한다 adsoftheworld.com'. 이것은 신뢰할 수없는 스크립트가 의심 할 여지없이 사용자가 스크립트를 실행하는 것처럼 다른 사이트의 내용을 읽지 못하게하는 보안 메커니즘입니다. 가장 안전한 솔루션은 서버 측 프록시를 사용하여 다른 사이트의 내용을 가져온 다음 웹 페이지와 동일한 출처에서 스크립트의 응답 내용을 제공하는 것입니다. – apsillers