我遇到了特定于我的 React Native Expo 开发构建的问题。我的应用程序中有多个 API,虽然其中大多数都可以正常工作,但在尝试向某个特定 API 发出请求时,我总是收到
AxiosError: Network Error
,但该特定 API 在邮递员中运行良好。
我仅在 Android 真实设备中运行我的项目
以下是有关该问题的一些详细信息:
环境:React Native Expo 开发构建
问题:仅在一个特定 API 中出现,其他 API 工作正常
错误信息:
AxiosError: Network Error
API:http://myIP:8080/api/v1/post/deal-posts
请求方式:[POST]
这是我的代码
const handleDealPost = async () => {
try {
const titleInFilename = title.replace(/\s+/g, "_");
const currentDate = new Date();
const formattedDate = currentDate.toLocaleDateString().replace(/-/g, "");
const imageKey = `${titleInFilename}_${formattedDate}.jpg`;
const formData = new FormData();
formData.append("dealURL", dealURL);
formData.append("title", title);
formData.append("company", company);
formData.append("discountedPrice", discountedPrice);
formData.append("originalPrice", originalPrice);
formData.append("description", description);
formData.append("category", category);
formData.append("dealType", dealType);
formData.append("image", {
uri: image.uri,
type: image.type,
name: imageKey,
});
formData.append("expiryDate", expiryDate.toString());
// console.log("FormData:", formData);
const response = await axios.post(
"http://MyIp:8080/api/v1/post/deal-posts",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
const result = response.data;
if (response.status === 201) {
Alert.alert("Success", result.message);
setPosts([...posts, result?.post]);
// navigation.navigate("BottomTabsNavigator");
navigation.navigate("Home");
setDealURL("");
setTitle("");
setCompany("");
setDiscountedPrice("");
setOriginalPrice("");
setDescription("");
setCategory(null);
setDealType(null);
setImage(null);
setExpiryDate("");
} else {
Alert.alert("Error", result.message);
}
} catch (error) {
console.error("Error:", error);
Alert.alert("Error", "An error occurred while posting the deal");
}
};
已检查 API 端点
使用 Postman 等工具测试了 API 端点[工作正常]
我已经在同一开发版本中使用其他 API 进行了测试,它们可以正常工作。
添加类型:在formData的值中
例如:
const formData = new FormData();
formData.append("myImage", { uri: "myFileURI", 名称:“我的文件名”, type: "image/jpeg", // 🎉 添加此!!!!!!! })