【问题标题】:React-Native | Unhandle promise JSON Parse error反应原生 |取消承诺 JSON Parse 错误
【发布时间】:2020-03-30 00:09:35
【问题描述】:

我尝试使用react-nativenodejs 中编写的一些api 创建一个简单的登录/注册系统。对于身份验证系统,我使用的是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');
    }
  }

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

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

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

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

  • ...来自框架内部的另外 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",
}

【问题讨论】:

  • 响应是什么样的?
  • @DaveNewton 我不明白你的意思

标签: node.js api react-native authentication


【解决方案1】:

我认为问题出在这里:

res.header('auth-token', token).send(token);

您基本上是按原样发送令牌,而不是作为 json。 然而,在您的前端代码中,您需要的是 json。

尝试这样做:

res.header('auth-token', token).send({token: token});

【讨论】:

  • 不,问题仍然存在
  • 尝试对您发回的所有数据执行相同操作:例如: res.status(400).send({message: 'Email not found'}) 您收到的消息暗示来自 API 的响应不是有效的 json。尝试在返回 response.json() 之前放置一个 console.log(response)
  • 我只是用console.log(response)的结果编辑我的问题
【解决方案2】:

在后端,使用res.json 而不是res.send:它将强制有效负载为JSON.stringifyed 和Content-Type。或者手动 jsonify 令牌:res.send(JSON.stringify(token))

作为pointed out earlier,您的问题是您的前端需要 JSON,但您的服务器发送纯数据:您的令牌(上面应用了JSON.stringify)将被封装在双引号中,使其在另一边。

【讨论】:

    【解决方案3】:

    将您的代码编辑为

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

    【讨论】:

      【解决方案4】:

      return response.json() 更改为response 并删除console.log()s。

      【讨论】:

      • 能否提供一段代码作为示例?
      猜你喜欢
      • 2017-07-16
      • 2018-04-19
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 2018-04-26
      • 2019-10-06
      相关资源
      最近更新 更多