【发布时间】:2019-12-11 10:27:41
【问题描述】:
我只是在我的 Simple react 本机应用程序中将用户 Singup 数据发布到 mongo-atlas。 通过邮递员;相同的代码工作正常并且成功发布用户数据,但是通过应用程序从用户那里获取数据会出现上述错误。前端和后端都在不同的文件夹上运行。我认为我没有正确处理前端部分。
这里是前端
export default class Formsignup extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
password: '',
showPass: true,
press: false,
};
this.showPass = this.showPass.bind(this);
}
showPass() {
this.state.press === false
? this.setState({showPass: false, press: true})
: this.setState({showPass: true, press: false});
}
getInput(text, field){
if(field == 'name')
{
this.setState({ name: text, })
}
else if(field == 'email')
{
this.setState({ email: text, })
}
else if(field == 'password')
{
this.setState({ password: text, })
}
}
submit(){
(async () => {
const rawResponse = await fetch('http://myIpAddress/api/user/register', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
password: this.state.password
})
});
const content = await rawResponse.json();
console.log(content);
})();
}
render() {
return (
<View style={styles.container}>
<UserInput
source={usernameImg}
placeholder="Username"
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
onChangeText = {(text) => this.getInput(text, 'name')}
/>
<UserInput
source={usernameImg}
placeholder="Email"
keyboardType="email-address"
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false}
onChangeText= {(text) => this.getInput(text, 'email')}
/>
<UserInput
source={passwordImg}
secureTextEntry={this.state.showPass}
placeholder="Password"
returnKeyType={'done'}
autoCapitalize={'none'}
autoCorrect={false}
onChangeText= {(text) => this.getInput(text, 'password')}
/>
<TouchableOpacity onPress = {()=> this.submit()}><Text>Submit Test</Text> </TouchableOpacity>
</View>
);
}
}
这是后端代码
router.post('/register', async (req, res) => {
const {error} = registerValidation(req.body);
if(error) return res.status(400).send(res.send(error.details[0].message));
//if user already in db
const emailExist = await User.findOne({email: req.body.email});
if(emailExist)
return res.status(400).send('Email Already Exist');
//hash the password bro
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//adding new user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
try{
const savedUser = await user.save();
res.send({user: user._id});
}catch(err){
res.status(400).send(err);
}
});
【问题讨论】:
-
请发布错误的屏幕截图。很难理解
-
打印您在控制台中发送的参数。根据我的说法,它的 500 错误。
标签: node.js react-native