【发布时间】: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