首页 > 解决方案 > 反应原生 | 取消承诺 JSON Parse 错误

问题描述

我尝试创建一个简单的登录/注册系统react-native,并使用nodejs. 对于身份验证系统,我使用的是jwt.

这是我的登录 API 的代码:

router.post('/login', async (req, res) => {
  const { error } = loginValidation(req.body);
  if ( error ) return res.status(400).send(error.details[0].message);

  //Checking if the mail exists
  const user = await User.findOne({email: req.body.email});
  if ( !user ) return res.status(400).send('Email not found');

  //Password is correct
  const validPassword = await bcrypt.compare(req.body.password, user.password);
  if ( !validPassword ) return res.status(400).send('Invalid password');
  
  //Create and assign the JWT
  const token = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET);
  res.header('auth-token', token).send(token);
});

这是用 react-native 编写的登录表单的代码:

<View style={{flex: 4, justifyContent: 'center', width: '100%'}}>
  <View style={{height: '70%', width: '100%'}}>
    <Text style={styles.question}>
      ACCEDI
    </Text>
    <View style={{width: '100%', paddingTop: '5%', paddingHorizontal: '10%'}}>
      <Form
        ref='form'
        options={options}
        type={User}
        value={this.state.value}
        onChange={this._onChange}
      />
    </View>
    <View style={{width: '100%', flexDirection:'row', alignItems: 'center'}}>
      <View style={{width: '10%'}}></View>
      <View style={{width: '70%'}}>  
        <TouchableOpacity style={styles.buttonpassword} onPress={ () => this.props.navigation.navigate('pippo') }>  
          <Text style={styles.signup}>
            Hai dimenticato la password?
          </Text>
        </TouchableOpacity>
      </View>  
    </View>
    <View style={{alignItems: 'center'}}>
      <View style={{height: 50, width: 150, alignItems: 'center', paddingTop: '2%'}}>
        <TouchableOpacity style={styles.button} onPress={this._handleAdd}>
          <Text style={styles.buttonText}>Login</Text>
        </TouchableOpacity>
      </View>
    </View>
  </View>
</View>

单击时,将调用login button该函数_handleAdd。该函数包含以下代码:

_handleAdd = () => {
    const value = this.refs.form.getValue();
    console.log(value);
    if ( value ) {
      const data = {
        email: value.username,
        password: value.password
      }
      fetch('http://localhost:3000/api/user/login', {
        method: 'POST',
        cache: 'no-cache',
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        }
      })
      .then((response) => {
        console.log(response);
        return response.json();
      })
      .then((body) => {
        console.log(body);
        alert(data);
      });
    }
    else {
      alert('All filds are require');
    }
  }

问题是单击按钮时。我有这个错误:

[未处理的承诺拒绝:SyntaxError:JSON 解析错误:意外的标识符“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9”]

  • node_modules/promise/setimmediate/core.js:37:14 在 tryCallOne

  • node_modules/promise/setimmediate/core.js:123:25 在

  • ... 来自框架内部的另外 8 个堆栈帧

编辑

console.log(response)返回这个:

Response {
  "_bodyBlob": Blob {
    "_data": Object {
      "blobId": "1311DDB1-F839-403E-9FEF-E7D3072F9AA1",
      "name": "login.html",
      "offset": 0,
      "size": 149,
      "type": "text/html",
    },
  },
  "_bodyInit": Blob {
    "_data": Object {
      "blobId": "1311DDB1-F839-403E-9FEF-E7D3072F9AA1",
      "name": "login.html",
      "offset": 0,
      "size": 149,
      "type": "text/html",
    },
  },
  "headers": Headers {
    "map": Object {
      "auth-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDhmN2UyNjdlZTIwNTI5ZDI1YjUzM2IiLCJpYXQiOjE1Njk2OTAxOTV9.K_sCEXG2obYE2y-wbX02Tqq_yG8rsOCZKr1YyZlurMQ",
      "connection": "keep-alive",
      "content-length": "149",
      "content-type": "text/html; charset=utf-8",
      "date": "Sat, 28 Sep 2019 17:03:15 GMT",
      "etag": "W/\"95-Gmy4omr48TDbf5eqm/r1yJHUQRg\"",
      "x-powered-by": "Express",
    },
  },
  "ok": true,
  "status": 200,
  "statusText": undefined,
  "type": "default",
  "url": "http://localhost:3000/api/user/login",
}

标签: node.jsapireact-nativeauthentication

解决方案


将您的代码编辑为

.then((response) => response.text())
.then((res) => {console.log("res is",res);}

推荐阅读