我想使用纯Java脚本在HTML页面上显示来自GET请求的pdf文件。api返回一个pdf文件。以下是api的邮递员响应:
到目前为止,我的代码如下:
function getImg() {
var url = "https://api.herokuapp.com/download"
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(null);
xhr.addEventListener('load', function() {
var responseObject = this.response;
var myImage = new Image();
myImage = this.response;
document.body.appendChild(myImage);
});
}
我得到了这个错误:
TypeError: Node.appendChild的参数%1不是对象。
如何做到这一点?任何帮助都是非常感谢的。BR KRESTEN
发布于 2019-11-22 17:19:25
下面是我解决这个问题的方法:
function getImg() {
var url = "https://secure.gravatar.com/avatar/3167fa1b890ffe735393de7d6296e32d?s=58&d=mm&r=g"
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
// xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));
// xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(null);
xhr.addEventListener('load', function() {
if (this.status === 200) {
let blob = this.response;
let myImage = new Image();
myImage.src = window.URL.createObjectURL(blob);
document.body.appendChild(myImage);
}
});
}
https://stackoverflow.com/questions/58990292
复制相似问题