javascript - XMLHttpRequest 错误 - "No ' Access-Control-Allow-Origin' header 出现在请求的资源上。”

标签 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 添加到我的 header 中,所以我使用了以下方法: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.

有人可以帮助我吗?

最佳答案

您面临的问题称为 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"/>

关于javascript - XMLHttpRequest 错误 - "No ' Access-Control-Allow-Origin' header 出现在请求的资源上。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43053379/

相关文章:

angular - 如何在 Typescript - Angular 8 中的字符串中添加新行

javascript - NodeJS 带 MongoDb : Removing a sub-field in a document

javascript - 如何测试抛出异常?

javascript - 数字和数字旁边的单词的正则表达式 javascript

rest - 使用 Rest API 获取 Azure DevOps 构建的构建结果

javascript 在 onopen 事件上出现 websocket 错误

javascript - PHP 变量到 JavaScript 变量到 HTML 跨度

java - 为什么我在此 REST 教程中得到 404?

rest - JAX-RS 2.0 更改默认实现

angularjs - Angular2 ngFor 产生额外的循环