XMLHttpRequest出错 - " No' Access-Control-Allow-Origin'标头出现在请求的资源上。"

时间:2017-03-27 17:59:16

标签: javascript rest angular http xmlhttprequest

我正在使用Angular 2创建应用程序的前端,我正在尝试使用XMLHttpRequest从第三方站点加载图像。

我的代码如下:

   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,所以我使用这个:request.setRequestHeader('Accept', '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.

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

您面临的问题称为CORS,https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS 通过提供标题Access-Control-Allow-Origin:*,您将能够通过ajax访问图像,但问题是为什么ajax?只需使用img标签吗?

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