使用“承载"身份验证令牌反应本机图像 [英] React Native Image with 'Bearer' authentication token

查看:43
本文介绍了使用“承载"身份验证令牌反应本机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React Native 中,我可以使用带有 <Image source={{uri: 'http://my.server.com/user/id/image/id.png'}}/>

In React Native I can use images with <Image source={{uri: 'http://my.server.com/user/id/image/id.png'}} />

问题是用户图像受我在标头中传递的 JWT 令牌保护.

The problem is that user images are protected by JWT token which I pass in the header.

是否可以以某种方式包含该附加标题?

Is it possible to somehow include that additional header?

我还有哪些选择?

谢谢!

推荐答案

您的选择如下:https://rnplay.org/apps/UowZmw(为了查看模拟器,在开发控制台中输入 document.querySelector('.editor-container').style.width = '50%', RNPlay 内容冗长,有点破).

Your options are this one: https://rnplay.org/apps/UowZmw (in order to see the simulator, type document.querySelector('.editor-container').style.width = '50%' in dev console, RNPlay is a bit broken with lengthy content).

基本上你要做的是:1. 将您的图像作为 blob 提供2. 使用 fetch() 将它们提取到应用程序中.3.使用base64数据作为uri属性

Basically what you do is to: 1. serve your images as blobs 2. fetch them with fetch() to the app. 3. use base64 data as content of uri property

在您的 componentWillMount() 中执行此操作:

Do this in your componentWillMount():

fetch(YOUR_IMAGE_URI, {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + 'TOKEN'
    }
  }
).then((res) => res.text())
.then((content) => {
  this.setState({
    base64: content
  })
})

您可能注意到我使用了 res.text() 而不是 res.blob().这是因为,在编写此代码时,RN 不支持 .blob().

You may notice I use res.text() instead of res.blob(). This is because, while writing this, RN doesn't support .blob().

这去render():

return (
  <Image style={styles.base64} source={{uri: this.state.base64}} />
)

这篇关于使用“承载"身份验证令牌反应本机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆