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

Jac*_* M. 4 authentication node.js jwt fetch-api react-redux

我有一个工作图像上传前端/后端代码工作。现在我希望能够在上传后从服务器获取图像。

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

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

fetch(imageURL, {
    method: 'GET',
    headers: {
        'x-access-token': localStorage.getItem('token')
}
Run Code Online (Sandbox Code Playgroud)

我只是得到一个 Form 对象作为响应:

<img alt="Your pic" src="[object FormData]">
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*aru 5

您可以尝试以下代码段:

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));
Run Code Online (Sandbox Code Playgroud)

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