【问题标题】:Error with XMLHttpRequest - "No 'Access-Control-Allow-Origin' header is present on the requested resource."XMLHttpRequest 出错 - “请求的资源上不存在 'Access-Control-Allow-Origin' 标头。”
【发布时间】:2017-08-20 13:44:01
【问题描述】:

我正在使用 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.

谁能帮帮我?

【问题讨论】:

  • adsoftheworld.com 必须在其响应中提供 Access-Control-Allow-Origin 标头,以允许您页面上的脚本读取响应的内容。这是一种安全机制,可防止不受信任的脚本读取其他站点的内容,就好像它们是运行脚本的毫无戒心的用户一样。最干净的解决方案是使用服务器端代理来获取其他站点的内容,然后将响应的内容提供给与您的网页相同的来源的脚本。

标签: javascript rest angular http xmlhttprequest


【解决方案1】:

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

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

【讨论】:

  • 嗨,img 标签正是我想要的……我还在学习 Angular,但我忘记了我有这个选项……我想我只是让解决方案过于复杂了……谢谢寻求帮助!
  • @Felipe Angular 2 祝你好运,很好的框架:)
猜你喜欢
  • 2014-09-22
  • 2015-04-04
  • 2017-04-28
  • 2019-10-24
  • 2013-11-29
  • 2014-07-28
  • 2014-01-19
相关资源
最近更新 更多