我正在為電子商務網站制作一個表單,該表單允許管理員/所有者將影像上傳到 Cloudinary。
影像已成功上傳到 Cloudinary,當我記錄回應(第 17 行的console.log(uploadedResponse))時,我的后端終端正在列印正確的資訊。
我遇到的問題是當我將回應發送到前端時,我沒有得到相同的資訊。回顧教程和檔案時,我已經對此進行了幾個小時的破解,但沒有運氣。
這是我后端的 server.js 代碼
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');
})
這是我的前端表單組件
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) 時的回應
{
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 終端的內容
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
為什么當它傳遞到前端時我沒有得到相同的資訊?非常感謝任何和所有幫助!
uj5u.com熱心網友回復:
在您的客戶端回應中,您將收到 ReadableStream 以回應正文。
為了從 ReadableStream 訪問資料,您需要呼叫轉換方法
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 資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497629.html
