使用"承载"身份验证令牌来反应本机映像

Leo*_*nti 6 react-native

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

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

是否有可能以某种方式包含额外的标题?

我还有什么其他选择?

谢谢!

小智 38

您可以在源道具中发送标头.

<Image
    source={
    { uri: 'https://yourdomain.com/get-image',
      headers: {
                Authorization: 'Bearer xyz'
               }
            }
     }/>
Run Code Online (Sandbox Code Playgroud)

您也可以指定其他参数: ImageSourcePropType.js

  • 这应该是IMO接受的答案! (3认同)

zvo*_*ona -1

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

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

在您的componentWillMount()

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

您可能会注意到我使用res.text()而不是res.blob(). 这是因为,在编写本文时,RN 不支持 .blob()。

这就是render()

return (
  <Image style={styles.base64} source={{uri: this.state.base64}} />
)
Run Code Online (Sandbox Code Playgroud)