【问题标题】:GET image from authenticated route从经过身份验证的路由中获取图像
【发布时间】:2017-08-02 08:04:08
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    你可以试试下面的sn-p:

    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

    【讨论】:

    • 谢谢 :) 我刚刚通过在发送到前端之前使用 base64 对文件进行编码并在前端图像标签中添加“data:image/png;base64,”之前让它工作图像二进制数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多