2017-03-27 1 views
0

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. 

아무도 도와 줄 수 있습니까?

+0

'페이지에 스크립트는 응답의 내용을 읽을 수의 응답에'액세스 제어 - 허용 - Origin' 헤더를 제공해야한다 adsoftheworld.com'. 이것은 신뢰할 수없는 스크립트가 의심 할 여지없이 사용자가 스크립트를 실행하는 것처럼 다른 사이트의 내용을 읽지 못하게하는 보안 메커니즘입니다. 가장 안전한 솔루션은 서버 측 프록시를 사용하여 다른 사이트의 내용을 가져온 다음 웹 페이지와 동일한 출처에서 스크립트의 응답 내용을 제공하는 것입니다. – apsillers

답변

3

CORS, https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS 헤더 액세스 제어 허용 원점 : *을 지정하면 이미지를 아약스를 통해 액세스 할 수 있지만 질문은 왜 아약스입니까? 바로 img 태그를 사용 하시겠습니까?

<img src="http://adsoftheworld.com/files/steve-jobs.jpg"/>

+0

안녕하세요, img 태그가 실제로 내가 찾고있는 태그였습니다 ... 아직 각도를 배우고 있으며이 옵션이 있다는 것을 잊어 버렸습니다 ... 솔루션을 너무 복잡하게 만들었습니다 ... 도움을 주셔서 감사합니다! – Felipe

+1

앵귤러 2, 좋은 프레임 워크로 @Felipe 행운을 빌어 요 :) – YoungLearnsToCoding

관련 문제