Im trying to fetch my login data using the login fetch method below which raises an error. I'm not sure why it raises this error and where its going wrong.
i get this error
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'res._bodyText')]
login fetch method
createUser: (username, password) => {
return (
fetch('http://192.168.0.140:80/auth/login/', {
method: 'POST',
dataType: 'jsonp',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
})
)
},
in my login.js
state = {
username: '',
password: ''
}
login = () => {
if (this.state.username === '') {
alert('Enter username !')
} else if (this.state.password === '') {
alert('Enter Password !')
} else {
api
.createUser(this.state.username, this.state.password)
.then((response) => response.json())
//If response is in json then in success
.then((responseJson) => {
//Success
console.log(responseJson)
})
//If response is not in json then in error
.catch((error) => {
//Error
console.error(error)
alert(error)
})
}
}
calling the login()
<TouchableNativeFeedback onPress={() => this.login()}>
<View style={styles.buttonContainer}>
<Text bold style={styles.buttonText}>
Login
</Text>
</View>
</TouchableNativeFeedback>
this could help you:
import {Alert} from 'react-native'
login = () => {
if (this.state.username === '') {
Alert.alert('Enter username !')
} else if (this.state.password === '') {
Alert.alert('Enter Password !')
} else {
api
.createUser(this.state.username, this.state.password)
.then((response) => {
if(response.ok) {
Alert.alert('Login successful')
}else{
Alert.alert('Check credentials')
}
})
//If response is in json then in success
//If response is not in json then in error
.catch((error) => {
//Error
Alert.alert('Check credentials')
})
}
}