【问题标题】:Possible Unhandled Promise Rejection (id: 1): SyntaxError: JSON Parse error: Unexpected identifier - React-Native可能未处理的 Promise Rejection (id: 1): SyntaxError: JSON Parse error: Unexpected identifier - React-Native
【发布时间】:2021-07-04 10:06:28
【问题描述】:

我是 react-native 的新学生。当我为我的移动前端使用 fetch 方法时,我收到了这样的错误消息。但我的后端工作正常。

This is my working back-end

但是当我使用我的前端时,我遇到了这样的错误。

This is my console log error

这是我糟糕的代码 -

import React,{useEffect,useState} from 'react';
import { Button ,TextInput} from 'react-native-paper';
import {
  ActivityIndicator,
  Text,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

const HomePage = (props) => {
   const [email,setEmail] = useState('loading');
   const Boiler = async ()=>{
      const token = await AsyncStorage.getItem('token');
    fetch('https://9b842786288e.ngrok.io/',{
    headers:new Headers({
      Authorization:'Test ' + token,
    }),
    }).then(res=>res.json())
    .then(data=>{
      console.log(data);
    }
    );
   };
useEffect(()=>{
   Boiler();
},[]);

   const logout = (props)=>{
      AsyncStorage.removeItem('token').then(()=>{
        props.navigation.replace('Login');
      });
   };

  return (
   <>
    <Text style={{fontSize:18}}>your email is {email}</Text>
    <Button
        mode="contained"
        style={{marginLeft:18,marginRight:18,marginTop:18}}
         onPress={() => logout(props)}>
        logout
      </Button>
   </>
  );
};

export default HomePage;

我真的需要你的帮助..谢谢。!

【问题讨论】:

  • 我认为你只是从后端返回一个字符串。尝试使用某个键返回一个对象,该对象的值等于您想要的字符串作为结果
  • app.get('/', requireToken, (req, res) => { res.send('Your email is ' + req.users.email); });
  • 这是我的后端,先生..?
  • 你在后端使用哪个框架

标签: javascript node.js reactjs react-native fetch


【解决方案1】:

您正在尝试使用 res.json() 将 text/plain 转换为 JSON 响应。

您应该从后端返回内容类型为 application/json 的 JSON 格式(作为标准/常见用例)或将 res.json() 替换为 res.text()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2021-07-09
    • 2022-11-18
    • 2018-04-12
    • 2017-01-25
    • 2018-08-06
    相关资源
    最近更新 更多