【问题标题】:Fetch image in React from Node.js request从 Node.js 请求中获取 React 中的图像
【发布时间】:2018-12-30 14:21:31
【问题描述】:

当需要时,React 会使用 Superagent 请求图像:

exports.getImgFromSection=function(id,request){
    request
       .get('/img/'+id)
       .end((error, response) => {
           if (!error && response) {
               console.log(response.file);
           } 
           else {
               console.log('There was an error fetching server', error);
           }
       })

}

Node.js 这样回答:

app.get("/img/:id",function(req, res){ 
   // check if exists and then
        res.sendFile(path.join(__dirname, './data/img/'+req.params['id']+'.png'));
});

但我不知道如何在 React 中获取图像。

console.log(response.file) 未定义。

console.log(response.files[0]) 未定义。

console.log(response.body) 为空。

console.log(response) 给我:

如何在 var 中获取图像?谢谢。

解决方案:

在 node.js 中:

var img = fs.readFile('./data/imagesUploaded/image.png', function (err, data) {
        var contentType = 'image/png';
        var base64 = Buffer.from(data).toString('base64');
        base64='data:image/png;base64,'+base64;
        res.send(base64);
    }); 

反应:

request
       .get('/img/'+imgID)
       .end((error, response) => {
        if (!error && response) {
            this.setState({img1:response.text})
        } else {
            console.log('There was an error fetching server', error);
        }
       })

【问题讨论】:

    标签: node.js reactjs image superagent sendfile


    【解决方案1】:

    我正在使用 axios(但它会相似)这是我获取图像的方式。

      const res = await axios.get(`/image/${imageId}`, {
        responseType: 'arraybuffer'
      });
      const imgFile = new Blob([res.data]);
      const imgUrl = URL.createObjectURL(imgFile);
    

    我认为响应类型在这里很重要.....但是我有节点将其作为流发送(因为我正在从 mongo 等检索......)

    【讨论】:

      【解决方案2】:

      解决方案:

      在 node.js 中:

      var img = fs.readFile('./data/imagesUploaded/image.png', function (err, data) {
              var contentType = 'image/png';
              var base64 = Buffer.from(data).toString('base64');
              base64='data:image/png;base64,'+base64;
              res.send(base64);
          }); 
      

      反应:

      request
             .get('/img/'+imgID)
             .end((error, response) => {
              if (!error && response) {
                  this.setState({img1:response.text})
              } else {
                  console.log('There was an error fetching server', error);
              }
             })
      

      【讨论】:

        【解决方案3】:

        使用 Axios 包在 React 中获取 POST 请求。 https://github.com/axios/axios

        https://github.com/axios/axios
        

        您需要发送请求以获取图像或发布图像。 只是一个例子。

        这是 React 中的一个函数。

         async sendEmail(name,interest,email,phone,message){
        
        
                  const form = await axios.post('/api/form',{
                    name,
                    interest,
                    email,
                    phone,
                    message
                })
        
            }
        

        这会将请求发送到此处的 Nodejs:

        app.post('/api/form',(req,res)=>{
        
                console.log(req.body);
                console.log(123);
                const output = `
            <p> You have a  Request</p>
                <h3> Contact Details </h3>
                <ul>
                    <li> Name : ${req.body.name}</li>
                    <li> Interest : ${req.body.interest}</li>
                    <li> Email : ${req.body.email}</li>
                    <li> Email : ${req.body.phone}</li>
                    <li> Email : ${req.body.message}</li>
                </ul>
            `;
        

        这也是 Fetch 请求的完成方式,但获取部分将在 React Code 中。

        无论如何,请阅读 Axios 文档。它将有各种关于它的例子。

        【讨论】:

        • Superagent 相当于 Axios,所以它不能解决我的问题。此外,您的示例显示了一个带有文本数据的表单,我需要一个来自 Node.js 的简单图像
        猜你喜欢
        • 2019-02-13
        • 2013-09-26
        • 2019-11-26
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 2020-08-25
        相关资源
        最近更新 更多