Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Erro Network request failed e JSON Parse error: Unrecognized token '

$
0
0

Estou fazendo um projeto para a faculdade (aplicativo mobile com reactnative, node, typescript e expo) e ao tentar utilizar a SDK do stripe,está ocorrendo os seguintes erros: Erro Network request failed JSONParse error: Unrecognized token '<'

utilizei esses dois videos como base para tentar fazer:https://www.youtube.com/watch?v=qiEwO_UrOrohttps://www.youtube.com/watch?v=SH2bi-1MUNM

Mesmo seguindo os mesmos passos e fazendo igual não consigo proceder.

sobre o erro de network, ao pesquisar, encontrei que poderia ser a URLincorreta no arquivo Config.ts, porém testei com várias diferentes enão dá certo: http://192.168.254...:19000 (IP do meu notebook);exp://192.168.254...:19000; http://127.0.0.1:19000;exp://127.0.0.1:19000; http://localhost:19002;http://localhost:19000;entre outros.

[enter image description here][1] [1]:https://i.stack.imgur.com/xHdxh.png

segue código:

> Config.ts        import {Platform} from 'react-native'    export const API_URL =     //se estiver rodando no android será aberto na URL...    Platform.OS === 'android' ? 'http://192.168.254.---:19000' : 'http://192.168.254.---:4242'> helpers.ts    import { Alert } from "react-native"    import {API_URL} from "./Config"    export async function FetchPublishableKey(){      try{        const response = await fetch(`${API_URL}/config`)        const {publishableKey} = await response.json()        return publishableKey      }catch(e){        console.log(e)        console.warn('unable to fetch. Is you runing the server?')        Alert.alert('Error', 'unable to fetch. Is you runing the server?')      }    }> index.tsx    import { ScrollView, Text, View } from "react-native";    import { StripeProvider } from "@stripe/stripe-react-native";    import { useEffect, useState } from "react";    import { FetchPublishableKey } from "../../../../helpers";    import styles from "./styles";    import Card from "./card";    import BackScreen from "../../../components/backScreen";    import { Feather } from "@expo/vector-icons";    import { Button } from "../../../components/buttons";    export default function Subscription({ navigation }: any) {        function handleNavigateToCard() {          navigation.navigate(Card)        }      const [publishableKey, setPublishableKey] = useState("");      useEffect(() => {        async function init() {          const publishableKey = await FetchPublishableKey();          if (publishableKey) {            setPublishableKey(publishableKey);          }        }      });      return (<StripeProvider publishableKey={publishableKey}><ScrollView contentContainerStyle={{ flexGrow: 1 }}><View style={styles.container}><View style={styles.header}><BackScreen /><Text style={styles.title}>Conta premium</Text><View /></View><View style={styles.content}><Feather name="check-circle" size={25} color={"#F0EFF4"} /><Text style={styles.containerText}>                  Torne-se um premium agora e fique livre de todos os anúncios :)</Text></View><View style={styles.content}><Feather name="help-circle" size={25} color={"#F0EFF4"} /><View style={styles.duvidas}><Text style={styles.containerText}>Como funciona?</Text><Text style={styles.containerText}>                    Por apenas R$ 10 00 (dez reais) você compra a versão premium do                    aplicativo de forma definitiva, ou seja, é feito apenas um                    pagamento! Desta forma, você nos ajuda a continuar melhorando o                    aplicativo :)</Text></View></View><Button title="Premium por R$ 10,00" onPress={handleNavigateToCard} /></View></ScrollView></StripeProvider>      );    }> styles.ts    import { StyleSheet } from 'react-native';    const styles = StyleSheet.create({        container: {            flex: 1,            padding: 20,            justifyContent: 'space-between',            backgroundColor: "#252525"        },        header: {            flexDirection: 'row',            justifyContent: 'space-between',            paddingTop: 20,        },        title: {            color: '#F0EFF4',            fontSize: 20,        },        text: {            color: '#F0EFF4',            fontSize: 18,            marginBottom: 10        },        content: {            marginTop: 20,            flex: 1,            flexDirection: 'row',        },        duvidas: {            flexDirection: 'column',        },        containerText: {            paddingLeft: 20,            paddingRight: 20,            color: '#F0EFF4',        },        //estilização card        cardField:{          width:"100%",          height:50,        },        input:{          height:50,          width:"100%",        }    });    export default styles;> card.tsx    import React, { useState } from "react";    import { Alert, Button, ScrollView, TextInput } from "react-native";    import styles from './styles'    import {CardField, useConfirmPayment} from '@stripe/stripe-react-native'    import { API_URL } from "../../../../Config";    export default function Card() {      const [name, setName] = useState("");      const {confirmPayment, loading} = useConfirmPayment()      const handlePayPress = async() => {        const response = await fetch(`${API_URL}/create-payment-intent`,{          method:'POST',          headers:{'Content-Type': 'application/json'          },          body: JSON.stringify({            paymentMethodType: 'card',            currency: 'BRL'          })        })        const {clientsecret} = await response.json()        const {error, paymentIntent } = await confirmPayment(clientsecret,{          type: 'Card',          billingDetails: {name}        })        if(error) {          Alert.alert(`Error code: ${error.code}`, error.message)        }else if (paymentIntent){          Alert.alert('Success', `Payment successful: ${paymentIntent.id}`)        }      }        return (<ScrollView><TextInput autoCapitalize="none"           placeholder="Name"          keyboardType="name-phone-pad"          onChange={(value) => setName(value.nativeEvent.text)}          style ={styles.input}          /><CardField           postalCodeEnabled={false}          style={styles.cardField}          /><Button title="Pay" onPress={handlePayPress} disabled={loading}/></ScrollView>      );    }

Não entendo muito de back-end então deve ter algo errado que não estouvendo, mas não consigo encontrar o que é e nem como arrumar


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>