【问题标题】:[Unhandled promise rejection: SyntaxError: Unexpected token i in JSON at position 7][Unhandled promise rejection: SyntaxError: Unexpected token i in JSON at position 7]
【发布时间】: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


【解决方案1】:

喂;在我看来,这与来自服务器端的 json 响应有关;这是一个提示尝试:

res.json 而不是 res.send 开始

您为 Fetch 函数编写的代码很弱,所以试试这个

let data = {
    method: 'POST',
    body: JSON.stringify({
      name: this.state.name,
      email: this.state.email,
      password: this.state.password
    }),
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
}
  fetch('http://10.105.4.135:3000/api/user/register', data).then(result=>result.json()) 
  .then((parsedResponse) => {
    console.warn('response',parsedResponse);
  }).catch((err) => {
    console.warn('error', err);
  })

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 2020-03-26
    • 2019-08-14
    • 2020-10-10
    • 1970-01-01
    相关资源
    最近更新 更多