Search code examples
javascriptnode.jsreactjsreact-nativefetch

Possible Unhandled Promise Rejection (id: 1): SyntaxError: JSON Parse error: Unexpected identifier - React-Native


I am a new student for react-native. when I using the fetch method for my mobile front-end, I got an error message like this. But my back end is just working fine.

This is my working back-end

But when I using my frond-end I got an error like this.

This is my console log error

and This Is my poor code -

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;

I Realy need your help..Thank You.!


Solution

  • You are trying to convert a text/plain to a JSON response with res.json().

    You should return from your backend a JSON format with content type application/json (as the standard/common use case) or replace res.json() with res.text()