【问题标题】:react, express and fetch - send and receive byteArrayreact, express and fetch - 发送和接收 byteArray
【发布时间】:2017-11-24 02:09:24
【问题描述】:

目前我正在寻找将base64 数据从Express server 发送/接收到我的React app. 的解决方案 Express 服务器正在读取图像,转换为base64,然后转换为byteArray 发送给客户端react-app.

  const request = require('request').defaults({ encoding: null });
  const base64 = require('base64-js');
    request.get(url, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      const buffer = new Buffer(body).toString('base64');
      const byteArray = base64.toByteArray(buffer);
      res.status(200).write(new Buffer(byteArray, 'binary'));
      res.end(undefined, 'binary');
    } else {
      res.status(response.statusCode).send(error.toString());
    }
  });

现在我如何在 react-app 中读取/解码这个 byteArray 以将此数据添加为图像 src(使用 fetch)?

【问题讨论】:

    标签: arrays reactjs express fetch-api


    【解决方案1】:

    <img src="data:image/gif;base64,R0lGODlhPQBEAPeoAJos......"> 您无需将 base64 转换为字节数组。您可以通过提供上述语法将其直接传递给图像源。然后显示所需的图像。

    【讨论】:

      【解决方案2】:

      您不需要转换返回的数据。并将其放在 img 元素中的 src 属性中。

      // if image data = { url: 'data:image/gif;xxxxxxxxxxxxx...' }
      
      class App extends React.Component {
      
        constructor() {
          super();
          this.state = { list: [] };
        }
      
          componentDidMount() {
          fetch('your-api-endpoint', {
            method: 'get',
          })
          .then(function(result) {
                  this.setState({ list: result });
          })
          .catch(function(error) {
              console.log(error)
          });
        }
          render() {
          const { list } = this.state;
          return (
              <div>
                {
                  list && list.length > 0
                list.map((img, index) => (
                  <img src={img.url} /> // include it as src
                ))
                :
                'no data'
              }
              </div>
          )
        }
      }
      

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 2020-02-09
        • 2020-09-09
        • 2021-06-30
        • 2017-12-31
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        相关资源
        最近更新 更多