node.js - 从经过身份验证的路由获取图像

标签 node.js authentication react-redux jwt fetch-api

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

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

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

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

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

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

除了将网址粘贴到“src”属性中之外,是否还有其他方法可以将图像放入 HTML“img”标签中,因为这会导致401(未经授权)

最佳答案

您可以尝试以下代码片段:

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

关于node.js - 从经过身份验证的路由获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45454974/

相关文章:

javascript - react - Redux 应用程序 : "Invalid attempt to spread non-iterable instance" Issue

node.js - 更新 Mongoose 中的模式以添加新属性

javascript - 将多个变量从express传递到jade

node.js - Neo4j 和 Node js 中的 session 过期

sockets - 通过 Node.js 上的套接字连接 Redis

javascript - 如何使用 react-table 仅重新呈现更新的行?

ios - ios 中的 soap 需要启用 cookie。如何在 SOAP 头中添加它?

php - Websockets 控制用户访问

php - 我可以在 PHP 中获取客户端用户名吗?

reactjs - react /Redux : how to hold login fail