首页 > 解决方案 > [未处理的承诺拒绝:SyntaxError:位置 7 处 JSON 中的意外标记 i]

问题描述

我只是在我的 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);
    }
}); 

标签: node.jsreact-native

解决方案


你好;在我看来,这与来自服务器端的 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);
  })

推荐阅读