0

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?

1
  • adsoftheworld.com must serve an Access-Control-Allow-Origin header 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. Commented Mar 27, 2017 at 18:07

1 Answer 1

3

The problem you are facing is called CORS, https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS By giving header Access-Control-Allow-Origin:*, you will be able to access the image through ajax, but the question is why ajax? just use img tag right?

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, well the img tag was really what I was looking for... I am still learning Angular and I forgot I had this option... I guess I just overcomplicated the solution... Thanks for the help!
@Felipe good luck with Angular 2, nice framework to go with:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.