从经过身份验证的路由获取图像

GET image from authenticated route

我有一个有效的 image-upload front/back-end 代码。现在我希望能够在上传后从服务器获取图像。

问题是图像必须在经过身份验证的路由之后,用户必须在 header 或 body 中传递 jwt 令牌。

当我尝试像这样获取图像时:

fetch(imageURL, {
    method: 'GET',
    headers: {
        'x-access-token': localStorage.getItem('token')
}

我刚收到一个表单 object 作为响应:

<img alt="Your pic" src="[object FormData]">

除了将 url 粘贴到 'src' 属性之外,还有什么方法可以将图像放入 HTML 'img' 标签中,因为它会导致 401 (Unauthorized)

您可以尝试以下代码段:

const myImage = document.querySelector('img');

// I make a wrapper snippet which will resolve to a objectURL
function fetchImage(url, headers) {
    return new Promise((resolve, reject) => {
        fetch(url, headers)
            .then(response => response.blob()) // sending the blob response to the next then
            .then(blob => {
                const objectUrl = URL.createObjectURL(blob);
                resolve(objectUrl);
            }) // resolved the promise with the objectUrl 
            .catch(err => reject(err)); // if there are any errors reject them
    });
}

fetchImage(imageUrl, {
    method: 'GET',
    headers: {
        'x-access-token': localStorage.getItem('token')
    }
})
    .then(objectUrl => myImage.src = objectUrl)
    .catch(err => console.log(err));

您可以在以下位置找到另一个供您尝试的示例: https://davidwalsh.name/convert-image-data-uri-javascript