我在 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 收到的错误
未捕获(承诺)语法错误:JSON 中的意外标记 < 在位置 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);
}
}