React Native的新手。我正在尝试使用Spencer Carli中的以下示例,通过fetch API使用FormData上传图像和数据。当我使用邮递员时,我的后端工作正常,图像可以毫无问题地上传到数据库存储中。但是当我尝试通过移动设备上传图片时,我得到了
upload error [SyntaxError: JSON Parse error: Unexpected identifier "Tunnel"]
下面是我的代码
const createFormData = (photo, body) => {
const data = new FormData();
data.append('file', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', ''),
});
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data;
};
const uploadPhotoHandler = async (photo) => {
const token = await AsyncStorage.getItem('token');
fetch('http://ba9737b7.ngrok.io/post', {
headers: {'Authorization': 'Bearer ' + token},
method: 'POST',
body: createFormData(photo, {
title: 'Golden twisted knots',
postType: 'hair',
duration: 45}),
})
.then(response => response.json())
.then(response => {
console.log('upload succes', response);
alert('Upload success!');
})
.catch(error => {
console.log('upload error', error);
alert('Upload failed!');
});
};
我认为问题出在这行
.then(response => response.json())
但我不知道为什么。
答案 0 :(得分:0)
问题是因为您没有收到JSON响应。当您尝试解析为JSON时。 您可以先检查响应状态代码来解决它,然后尝试尝试。
const uploadPhotoHandler = async (photo) => {
const token = await AsyncStorage.getItem('token');
fetch('http://ba9737b7.ngrok.io/post', {
headers: {'Authorization': 'Bearer ' + token},
method: 'POST',
body: createFormData(photo, {
title: 'Golden twisted knots',
postType: 'hair',
duration: 45}),
})
.then(response => {
//If the response status code is between 200-299, if so
if(response.ok) return response.json();
//if not, throw a error
throw new Error('Network response was not ok');
})
.then(response => {
console.log('upload succes', response);
alert('Upload success!');
})
.catch(error => {
console.log('upload error', error);
alert('Upload failed!');
});
};