2

I am very new to this and would like to know how to do this properly. My back end is a django rest framework and my front is under react native. my back end has users and my application requires token authentication to identify a user. After exploring react native further i know i will need to use fetch and post methods to access the api.

successful authentication should get the user to navigate to the main page

This is what i have so far:

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    KeyboardAvoidingView,
    TouchableOpacity,
    AsyncStorage,
} from 'react-native';

export default class Form extends Component<{}> {

constructor(props){
    super(props);
    this.state = {
        username: "",
        password: "",

    }
}

componentDidMount(){
    this._loadInitialState().done();

}
_loadInitialState= async() => {
    var value = await AsyncStorage.getItem('user');
    if (value !== null){
        this.props.navigation.navigate('Main')
    }
}


render(){
    return(
        //<KeyboardAvoidingView style={styles.wrapper}>
        <View style={styles.container}>
            <TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Username"
                       onChangeText={ (username) => this.setState({username}) }
                       underlineColorAndroid='transparent' onSubmitEditing={()=> this.password.focus()}/>

            <TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Password"
                       onChangeText={ (password) => this.setState({password}) }
                       underlineColorAndroid='transparent' secureTextEntry={true} ref={(input) => this.password = input}/>
            <TouchableOpacity style={styles.button} onPress={this.login}>
                <Text style={styles.textButton}>{this.props.type}</Text>
            </TouchableOpacity>
        </View>
        //</KeyboardAvoidingView>
    );
}
login = () => {

    //alert(this.state.username);
    fetch('http://.../token-auth/', {
        method: 'POST',
        headers : {
            'Authorization': 'Token' + '4bd97c6a3da72d83cee684617f43718811db4d88', #random token
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password,
        })
    })
        .then((response) => response.json())
        .then((res) => {
            //alert(res.message);
            if (res.success === true){
                AsyncStorage.setItem('user', res.user);
                this.props.navigation.navigate('Main');
            }
            else{
                alert(res.message);

            }
        })
        .done();

I am getting undefined response. token-auth is my api response that returns the token. I know axios is another way to perform this, but do i really have to use axios?

this is the output from the console:

03-10 14:44:59.491  9464  9561 I ReactNativeJS:   statusText: undefined,
03-10 14:44:59.491  9464  9561 I ReactNativeJS:   headers:
03-10 14:44:59.491  9464  9561 I ReactNativeJS:    { map:
03-10 14:44:59.491  9464  9561 I ReactNativeJS:       { allow: [ 'POST, OPTIONS' ],
03-10 14:44:59.491  9464  9561 I ReactNativeJS:         'content-type': [ 'application/json' ],
03-10 14:44:59.491  9464  9561 I ReactNativeJS:         'x-frame-options': [ 'SAMEORIGIN' ],
03-10 14:44:59.491  9464  9561 I ReactNativeJS:         server: [ 'WSGIServer/0.1 Python/2.7.14' ],
03-10 14:44:59.491  9464  9561 I ReactNativeJS:         date: [ 'Sat, 10 Mar 2018 14:44:53 GMT' ] } },
03-10 14:44:59.491  9464  9561 I ReactNativeJS:   url: 'http://:8080/token-auth/',
03-10 14:44:59.491  9464  9561 I ReactNativeJS:   _bodyInit: '{"token":"4bd97c6a3da72d83cee684617f43718811db4d88"}',
03-10 14:44:59.491  9464  9561 I ReactNativeJS:   _bodyText: '{"token":"4bd97c6a3da72d83cee684617f43718811db4d88"}' }
03-10 14:44:59.500  9464  9561 E ReactNativeJS: undefined is not an object (evaluating 'res.success')

Have i missed something crucial? a couple of pointers will be much appreciated. Thanks

1 Answer 1

5

One minor but crucial mistake in your code is the missing space in

'Authorization': 'Token' + '4bd97c6a3da72d83cee684617f43718811db4d88'

change it to

'Authorization': 'Token ' + '4bd97c6a3da72d83cee684617f43718811db4d88'

And you might come a step further. I compared your fetch script with mine and it is quite similar. During developing it might be helpful to change

.then((response) => response.json())

to

.then((response) => console.log(response))

To be sure what the problem really is.

The response did not contain any success key. Instead of

if (resjson.success===true ){

one should have

if (resjson.token ){
Sign up to request clarification or add additional context in comments.

9 Comments

good gracious... one tiny space is causing a lot of headache.. / JSON Parse Error expected "}" is the problem :D
Sometimes the spaces are important ;-) I guess that there are some django errors thrown as well. Did you try console.log(response)? Also you could try to catch the error .catch(err=>console.log(err))
i have yes i followed your advised on the header 'Authorization': 'Token ' + '4bd97c6a3da72d83cee684617f43718811db4d88' then JSON parse error '}' appeared then i did this, "Authorization": "Token " + "4bd97c6a3da72d83cee684617f43718811db4d88" and now a new error came undefined is not an object(evaluating 'res.success')
after including console.log(response) i do indeed get undefined is not an object (evaluating' res.success')
Yes res.success is throwing undefined. Since console.log(response) does not pass anyting to the .then(). What you should look for is the output of the console.log() in the consol.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.