【发布时间】:2021-05-27 11:06:30
【问题描述】:
对于我的编辑个人资料页面,我需要调用 2 个 API 来更改个人资料图片。我用fetch()。
API 的工作方式是首先我发送用户 ID,并期望响应是上传 ID 的数字。
然后我将该 id 作为图像的名称发送到下一个 API。
我也将我的 base64 图像存储到一个状态,第二个 API 无法正常工作,因为我假设我无法访问此函数中的图像状态。
我无法在它给我的函数中记录图像:
PayloadTooLargeError: request entity too large
这是我的实现:
const [image, setImage] = useState(null);
const [imageUploading, setImageUploading] = useState(false);
const [uploadId, setUploadId] = useState('');
const userData = useSelector(state => state.user.userData)
const logOutHandler = async () => {
try {
await AsyncStorage.removeItem('loginData').then(() => {
props.navigation.reset({
index: 0,
routes: [{ name: 'Login' }]
})
})
} catch (e) {
console.log(e)
}
console.log('Done.')
}
const allowAccess = async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
} else {
pickImage()
}
}
}
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
base64: true
});
if (!result.cancelled) {
setImage(result.base64);
uploadImage()
}
};
const uploadImage = () => {
fetch('URL',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"id": userData.id
})
})
.then(response => response.json()) // pass the data as promise to next then block
.then(data => {
setUploadId(data)
})
.catch((err) => console.log(err))
fetch('URL2',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"fileName": uploadId,
"fileBase64String": image,
"folderName": 'User',
"fileExtension": '.jpg'
})
})
.then(response => response.json()) // pass the data as promise to next then block
.then(data => {
console.log('here....' ,data)
})
.catch((err) => console.log(err))
}
【问题讨论】:
-
我建议的另一件事是您使第二个 API 同步。由于 API 是依赖的,因此将 fetch("For 2nd API") 移到 then 块中。
-
@KaranGaur 感谢您的回复,它给了我错误:“errors”:Object {“”:Array [“无法读取请求表单。超出表单密钥长度限制2048。”,], }, "status": 400, "title": "出现一个或多个验证错误。", "traceId": "|9776e7a3-4a9998d0c78f9ed8.", "type": "tools.ietf.org/html/rfc7231#section-6.5.1", }
-
尝试使用多部分作为内容类型标题 - “multipart/form-data”
-
不走运,对象 { "status": 415, "title": "Unsupported Media Type", "traceId": "|9776e7a9-4a9998d0c78f9ed8.", "type": "tools.ietf.org/html/rfc7231#section-6.5.13" , } 我也将控制台记录为呼叫顺序,但似乎他们运行购买订单。
-
multipart 只能用于第二个 API 调用。您也可以对后端进行更多说明吗?
标签: javascript reactjs react-native fetch