【问题标题】:How to GET image in reactjs from api?如何从 api 获取 reactjs 中的图像?
【发布时间】:2018-10-24 22:11:28
【问题描述】:

在使用 JWT 令牌进行验证后,我正在从 nodejs API 获取图像。 我在浏览器中收到 GET 200 ok 响应网络标题和图片可以在预览中看到,但我不能在我的应用程序中使用它。

我肯定做错了什么。请让我知道从 API 显示图像的正确方法。 在我的后端 nodejs 上,我使用 res.sendFile 来发送文件。

class Card extends Component {
 constructor({props, pic, token}) {
super(props, pic, token);
this.state = { 
  pic: pic,
};

urlFetch(data) {
 fetch(data, { 
 headers: new Headers({
 'authorization': `Bearer ${this.props.token}`, 
 'Content-Type': 'application/json'
 })
})
.then(response => {
 if (response.statusText === 'OK') {
  return data   // OR return response.url
  }
 })
}

render() {
const { pic } = this.state;

 return (
        <div>
          <img style={{width: 175, height: 175}} className='tc br3' alt='none' src={ this.urlFetch(pic) } />
        </div>
       );
      }
     }

【问题讨论】:

  • src={ pic }应该可以工作。
  • @hurricane 它不会。获取的图像和状态属性pic 之间没有链接。 urlFetch 的回调中没有 setState 发生
  • @hurricane 正如我已经提到的,我在后端使用 JasonWebToken 来获取图像。
  • api返回图片url还是图片文件本身?
  • @roxxypoxxy 我可以在浏览器网络中看到图像 -> 预览。仅当后端授权成功时,我才会在我的 fetch 中返回图像 url。

标签: javascript node.js reactjs fetch-api


【解决方案1】:
 var myHeaders = new Headers();
 myHeaders.append("response", "image/jpeg");
 myHeaders.append("psId", "");
 myHeaders.append("x-api-key", "Z7dwTzHQrklCh7bvSWqhNrDTPZiLblYS");
 myHeaders.append(
    "Authorization",
    "Bearer token"
 );

var raw = "";

var requestOptions = {
  method: "GET",
  headers: myHeaders,
  //body: raw,
  redirect: "follow",
};
let response = await fetch(
  "YourURL",
  requestOptions
)
.then((response) => response)
.then((result) => result)
.catch((error) => console.log("error", error));

 res = await response.blob();

然后在你的 html 或 jsx 文件中的 image 标签中你可以这样做:

 <img src={window.webkitURL.createObjectURL(res)} />

【讨论】:

  • 不要这样做。您不应该在客户端代码中公开 api 密钥。
【解决方案2】:

我能够使用与此类似的模式在 React 中渲染来自后端调用的图像:react hooksaxiosURL.createObjectURL

我使用URL.createObjectURL(blob) 方法并使用axios 配置{ responseType: 'blob' } 来确保数据类型适合。

const ImageComponent = (imageIds) => {
  const [images, setImages] = React.useState([])

  React.useEffect(() => {
    async function getImage (id) {
      let imageBlob
      try {
        imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
      } catch (err) {
        return null
      }
      return URL.createObjectURL(imageBlob)
    }
    async function getImages () {
      const imageArray = []
      for (const id of imageIds) {
        imageArray.push(await getImage(id))
      }
      setImages(imageArray)
    }

    getImages()
  }, [imageIds])

  return images.map((img, i) => {
    return <img src={img} alt={`image-${i}`} key={i} />
  })
}

[编辑]:如果您的 api 是受保护的路由,只需确保您的 axios http 客户端已使用令牌初始化

【讨论】:

    【解决方案3】:

    这是我久经考验的获取数据的方法:

    componentDidMount(){
        fetch('https://www.yoursite.com/api/etc', {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
        })
        .then((response) => {
          return response.text();
        })
        .then((data) => {
          console.log( JSON.parse(data) )
          this.setState{( pic: JSON.parse(data) )}
        })
    }
    

    然后在你的img中

    src={ this.state.pic }
    

    【讨论】:

    • 请再次阅读问题。这与承诺无关。我必须在我的应用中使用从后端发送的图像。
    • 你有没有在你的 fetch 方法中尝试过 this.setState{(pic: data)} ,然后 src={ this.state.pic } ?
    • 那么如何调用函数来请求带有Token的图片呢?
    • 我通常在componentDidMount里面做
    • 代替response.text和parse,我们也可以这样做 .then((response) => { return response.json() }) .then((data) => { console.log ( "响应是 " + data ) })
    【解决方案4】:

    我找到了答案。这里是:

    Working with the Fetch API - Google docs

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2022-01-18
      • 1970-01-01
      • 2023-01-18
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 2017-02-16
      相关资源
      最近更新 更多