javascript - React Native Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
问题描述
我在 React Native 中的代码有一个小问题,错误显示Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0,我只想用新密码更新现有密码。
const getProfile = async(token) =>{
let jsonValue = await AsyncStorage.getItem('@storage_Key')
jsonValue = JSON.parse(jsonValue);
setProfile(jsonValue);
console.log(config.API_URL + '/users/'+ jsonValue.userId)
fetch(config.API_URL + '/users/'+ jsonValue.userId, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
},
})
.then((response) => response.json().then(data=>({status:response.status, body:data})) )
.then((response) => {
console.log("User information = ",response);
if(response.status==200)
{
if(response.body.length > 0)
{
let _UserData = {};
setUserData(response.body[0]);
setUserPassword(decodeURI(response.body[0].Password))
console.log("response.body[0]",response.body[0]);
}else{
setErrortext(response.body.msg);
setPreventSubmit(true);
}
}else{
setErrortext(response.body.msg);
setPreventSubmit(true);
};
})
}
const handleSubmit = async(valuesToSubmit) => {
let finalValidationPassed=true;
if(valuesToSubmit['password1'] == valuesToSubmit['password2'] & valuesToSubmit['password2'] == valuesToSubmit.userdata){
let _data = {
UsersId: UserData.UsersId,
Password: valuesToSubmit.userdata
}
console.log("_data",_data)
if(finalValidationPassed)
{
setErrortext("");
fetch(config.API_URL + '/user/password', {
method: 'PUT',
body: JSON.stringify(_data),
headers: {
'Authorization': 'Bearer '+ token,
'Content-Type': 'application/json',
},
})
.then((response) => response.json().then(data=>({status:response.status, body:data})) )
.then((response) => {
console.log("data",response);
if(response.status==200){
setIsEdit(false);
alert("Profile Updated!");
refetch();
}else{
setErrortext(response.body[0]?.msg);
setErrortext(response.body[0]?._msgerror);
}
});
}else{
alert("Error");
}
}else{
alert("Sorry, submission failed. Please check your data entries.");
}
}
<Formik
enableReinitialize
initialValues={{userdata:UserData.Password, password1: "", password2: "" }}
onSubmit={(values) =>{ handleSubmit(values)}}
>
{(props) => (
<SafeAreaView>
<View style={formStyles.SectionStyle}>
<Text>CURRENT PASSWORD</Text>
<TextInput
name="Password"
value={props.values.userdata}
style={formStyles.inputStyle}
underlineColorAndroid="#f000"
placeholderTextColor="#8b9cb5"
keyboardType="email-address"
secureTextEntry={true}
onChangeText={props.handleChange('userdata')}
/>
</View>
{(props.errors.Password && props.touched.Password) && <Text style={formStyles.errorText}>{errors.Password}</Text> }
<View style={formStyles.SectionStyle}>
<Text>SET NEW PASSWORD</Text>
<TextInput
name="password1"
value={props.values.password1}
style={formStyles.inputStyle}
underlineColorAndroid="#f000"
placeholderTextColor="#8b9cb5"
keyboardType="email-address"
onChangeText={props.handleChange("password1")}
/>
</View>
{(props.errors.Password && props.touched.Password) && <Text style={formStyles.errorText}>{errors.Password}</Text> }
<View style={formStyles.SectionStyle}>
<Text>CONFIRM NEW PASSWORD</Text>
<TextInput
name="password2"
value={props.values.password2}
style={formStyles.inputStyle}
underlineColorAndroid="#f000"
placeholderTextColor="#8b9cb5"
keyboardType="email-address"
onChangeText={props.handleChange("password2")}
/>
</View>
{(props.errors.Password && props.touched.Password) && <Text style={formStyles.errorText}>{errors.Password}</Text> }
<TouchableOpacity
style={formStyles.buttonStyle}
activeOpacity={0.5}
disabled={!props.isValid}
onPress={props.handleSubmit}
>
<Text style={formStyles.buttonTextStyle}>RESET PASSWORD</Text>
</TouchableOpacity>
</SafeAreaView>
)}
</Formik>
这是来自 api 的返回
这是我从 console.log 收到的错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
错误指向这里
console.log("_data", _data)
这是来自 api 的响应
API
async function updateUserPassword(req, res, next){
params = req.body;//post
let validation_rules = {
UsersId:'required|integer',
Password: 'required'
}
console.log("validation_rules",validation_rules);
let validation = new Validator(params, validation_rules);
if(validation.passes())
{
try
{
let resultsplayer = await userprofile.getProfile(params)
if(resultsplayer.rowCount > 0){
let results = await userprofile.updateUserPassword(params)
if(results.rowCount > 0){
res.status(200).json(results.rows);
}else{
res.status(304).json({"message":"Update Failed"});
}
}else{
res.status(404).json({"message":"Record Not Found"});
}
}catch(err){
console.log("-----result data error-----\n", err);
res.status(500).json(err);
}
}else{
res.status(400).json(validation.errors);
}
}
解决方案
推荐阅读
- laravel - 在 IIS 10 中使用 laravel websocket 时出错
- javascript - 唯一配对数组元素的最佳方法(其中元素是原始类型和数组)
- xcode - 如何在 CarPlay 上显示歌曲
- timer - 可以同时执行两个 Linux 内核计时器处理程序吗?
- python - 过滤在 Pandas 中读取的 CSV 数据
- python - Scrapy:谁能告诉我为什么这段代码不能让我抓取后续页面?
- python - 将复杂 JSON 转换为 excel 或 CSV
- java - Android 8 之后有多少静态广播接收器无法工作?
- firebase - 颤动时无法从firestore获取文件
- c - Why cant I cast a void* back to an int* and dereference it?