I am creating the front end of an application using Angular 2 and I am trying to load an image from a third party site using XMLHttpRequest.
My code is below:
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;
}
And this is the code that I am using to test it:
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();
});
});
I've looked around the internet and several pages said that I should add image/jpeg to my headers, so I did it using this: request.setRequestHeader('Accept', 'image/jpeg');, however I still get the error below whenever I run this code:
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.
Can anyone help me?
adsoftheworld.commust serve anAccess-Control-Allow-Originheader in its response that allows scripts on your page to read the contents of the response. This is a security mechanism to prevent untrusted scripts from reading the contents of other sites as if they were the unsuspecting user running the script. The cleanest solution is to use a server-side proxy to fetch the contents of the other site and then serve the contents of the response to your script on the same origin as your webpage.