Home > Mobile >  Node/Express logging the correct response, but React frontend logging something completely different
Node/Express logging the correct response, but React frontend logging something completely different

Time:06-28

I'm working on a form for a ecommerce site that allows the admin/owner to upload Images to Cloudinary.

The image is uploading to Cloudinary successfully, and when I log the response (console.log(uploadedResponse) on line 17) my backend terminal is printing the correct information.

The problem I'm having is when I send the response to the frontend I am not getting the same information. I've been hacking at this for a few hours going back through the tutorial and docs with no luck.

Here is my server.js code from the backend

const express = require('express');
const server = express();
const cors = require('cors');
const { cloudinary } = require('./utils/cloudinary');

server.use(cors())
server.use(express.json({ limit: '50mb'}))

server.post('/api/upload', async (req, res) => {
    try{
        const fileString = req.body.data;

        const uploadedResponse = await cloudinary.uploader.upload(fileString, {
            upload_preset: 'dev_setups'
        })
        
        console.log(uploadedResponse);
        
        res.status(200).json(uploadedResponse);
    }catch(error){
        console.log(error);
        res.status(500).json({ message: 'Something went wrong'})
    }
})

server.listen(9000, () => {
    console.log('server listening on port 9000');
})

Here is my frontend form component

import React, {useState} from 'react';

const Upload = () => {

    const [previewSource, setPreviewSource] = useState('');

    const handleChange = e => {
        const file = e.target.files[0];
        previewFile(file);
    }

    const previewFile = file => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = () => {
            setPreviewSource(reader.result);
        }
    }

    const handleSubmit = e => {
        e.preventDefault();
        if(!previewSource) return;

        fetch('http://localhost:9000/api/upload', {
            method: 'POST',
            body: JSON.stringify({data: previewSource}),
            headers: {'Content-Type': 'application/json'}
        })
        .then(resp => {
            console.log('hitting response');
            console.log(resp)
        })
        .catch(error => {
            console.log(error);
        })
    }

    return(
        <div>
            <h1>Upload</h1>
            <form onSubmit={handleSubmit}>
                <input
                    type="file"
                    name='image'
                    onChange={handleChange}
                />
                <button type='submit'>Submit</button>
            </form>

            {previewSource && (
                <img src={previewSource} alt='chosen' />
            )}
        </div>
    )
}

export default Upload;

Here is the response when I console.log(uploadedResponse) on my backend

{
  asset_id: 'f5c8e1d684bb54aa4f3a1d75822f8968',
  public_id: 'pictures/yb5snsg0rswrlh1q3utz',
  version: 1656310653,
  version_id: 'b445893bf893ff2d99cd238b67ffc0e3',       
  signature: '0282cd43e314ef0b8afb04106a1ef109aab956d4',  width: 1584,
  height: 396,
  format: 'png',
  resource_type: 'image',
  created_at: '2022-06-27T06:17:33Z',
  tags: [],
  bytes: 601916,
  type: 'upload',
  etag: 'b9b2383b9be7af4f4d77965789a90cb5',
  placeholder: false,
  url: 'http://res.cloudinary.com/andrewg0427/image/upload/v1656310653/pictures/yb5snsg0rswrlh1q3utz.png',      
  secure_url: 'https://res.cloudinary.com/andrewg0427/image/upload/v1656310653/pictures/yb5snsg0rswrlh1q3utz.png',
  folder: 'pictures',
  access_mode: 'public',
  api_key: '745648355657514'
}

When the frontend receives the response this is what gets logged to my devtools terminal

Response {type: 'cors', url: 'http://localhost:9000/api/upload', redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: false
[[Prototype]]: ReadableStream
bodyUsed: false
headers: Headers
[[Prototype]]: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:9000/api/upload"
[[Prototype]]: Response

Why am I not getting the same information when it gets passed to the frontend? Any and all help is much appreciated!!

CodePudding user response:

In your client-side response, you are receiving ReadableStream in response to the body.

In order to access the data from a ReadableStream, you need to call conversion method

 const handleSubmit = e => {
        e.preventDefault();
        if(!previewSource) return;

        fetch('http://localhost:9000/api/upload', {
            method: 'POST',
            body: JSON.stringify({data: previewSource}),
            headers: {'Content-Type': 'application/json'}
        })
        .then((response)=> response.json())
        .then(data => {
            console.log('hitting response');
            console.log(data)
        })
        .catch(error => {
            console.log(error);
        })
    }

See the changes I did .then((response)=> response.json()) it is converting your ReadableStream into a json data.

  • Related