简体   繁体   中英

Error with XMLHttpRequest - “No 'Access-Control-Allow-Origin' header is present on the requested resource.”

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?

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"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM