我在我的反應專案中使用 fetch 而不是 axios
我的這種方法可以與 axios 一起正常作業以在服務器上上傳影像
上傳圖片功能
<Upload customRequest={dummyRequest} className="upload-btn-container" onChange={onChange}>
<Button className="btn custom-upload-btn">Upload Image</Button>
</Upload>
const uploadPicture = async (data) =>{
const value = await getUploadPicture(data)
if(value.value.data.status){
await addImage(value.value.data.data)
}
}
const onChange = async (info) => {
for (let i = 0; i < info.fileList.length; i ) {
const data = new FormData();
data.append('file', info.fileList[i]);
data.append('filename', info.fileList[i].name);
setImgName(info.fileList[i].name)
let value = await uploadPicture(data);
}
};
return axios({
method: 'post',
url: `${NewHostName}/upload`,
headers: {
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('authToken')
},
data:data
})
.then(response => {
return response
}).catch(err => {
console.log("err", err)
})
而當我對 fetch 執行相同操作時,它會在后端引發錯誤"Cannot read property of split of undefined"
return fetch(`${NewHostName}/upload`, {
method: "post",
headers: {
"Content-Type": "application/json",
Authorization: localStorage.getItem('authToken'),
},
body: JSON.stringify(data),
// body :data
})
.then((res) => {
return res.json();
})
.then((payload) => {
return payload;
})
.catch((err) => {
throw err;
})
不知道這背后的原因是什么
這是我的backend上傳 api
const handler = async (request, reply) => {
try {
const filename = request.payload.filename
const fileExtension = filename.split('.').pop()
AWS.config.update({
accessKeyId: Config.get('/aws').accessKeyId,
secretAccessKey: Config.get('/aws').secretAccessKey,
region: Config.get('/aws').region
})
const s3 = new AWS.S3({
params: {
Bucket: Config.get('/aws').bucket
}
})
const Key = `/${shortid.generate()}.${fileExtension}`
const obj = {
Body: request.payload.file,
Key,
ACL: 'public-read'
}
s3.upload(obj, async (err, data) => {
if (err) {
return reply({ status: false, 'message': err.message, data: '' }).code(Constants.HTTP402)
} else if (data) {
return reply({ status: true, 'message': 'ok', data: data.Location }).code(Constants.HTTP200)
}
})
} catch (error) {
return reply({
status: false,
message: error.message,
data: ''
})
}
}
uj5u.com熱心網友回復:
data是一個FormData物件。
在您的原始代碼中,當您說'Content-Type': 'application/json'. 可能 Axios 識別出您已將 FormData 物件傳遞給它并忽略您嘗試覆寫 Content-Type。
另一方面,您的 fetch 代碼表示body: JSON.stringify(data)哪個嘗試對 FormData 物件進行字串化,并最終得到"{}"哪個沒有您的資料。
- 不要聲稱您正在發送 JSON
- 不要通過您的 FormData 物件
JSON.stringify
uj5u.com熱心網友回復:
對于影像上傳,您不使用 JSON.stringify(data)。您可以嘗試使用 formData 并附加帶有表單資料的影像檔案。
var formdata = new FormData();
formdata.append("image", data);
uj5u.com熱心網友回復:
你檢查了嗎
const filename = request.payload.filename
存在嗎?
密鑰真的是有效載荷嗎?以下內容不會對您的代碼進行任何更改:
.then((payload) => {
return payload;
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486420.html
標籤:javascript 节点.js 反应 文件
