首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点/Express记录正确的响应,但响应前端日志记录完全不同

节点/Express记录正确的响应,但响应前端日志记录完全不同
EN

Stack Overflow用户
提问于 2022-06-27 06:27:46
回答 1查看 125关注 0票数 0

我正在为电子商务网站开发一个表单,允许管理员/所有者将图片上传到Cloudinary。

图像正在成功地上传到Cloudinary,当我在第17行记录响应(console.log(uploadedResponse) )时,后端终端将打印正确的信息。

我遇到的问题是,当我将回复发送到前端时,我没有得到相同的信息。几个小时以来,我一直在破解这个问题,在没有运气的情况下,回顾了一下教程和文档。

下面是后端的server.js代码

代码语言:javascript
复制
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');
})

这是我的前端表单组件

代码语言:javascript
复制
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;

下面是我在后端console.log(uploadedResponse)时的响应

代码语言:javascript
复制
{
  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'
}

当前端接收到响应时,这就是记录到我的devtools终端的内容

代码语言:javascript
复制
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

为什么当信息传递到前端时,我没有得到相同的信息?所有的帮助都是非常感谢的!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-27 07:04:31

在您的客户端响应中,您正在接收响应于身体的ReadableStream。

为了从ReadableStream访问数据,需要调用转换方法

代码语言:javascript
复制
 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);
        })
    }

请看我所做的更改,.then((response)=> response.json())正在将您的ReadableStream转换为json数据。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72767753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档