我正在尝试从Django authtoken的restframework中提取授权令牌,但似乎无法从请求中获取响应令牌。通过使用Postman,我得到了状态为200的令牌。但是,当我尝试在代码中使用Fetch进行操作时,我得到了状态200,这是一个不同的响应。 Response from POST request
从服务器的角度来看,我收到了200请求的POST请求。我相信它只是响应的格式,但我似乎不知道如何处理。
下面是我的登录表单的代码。
import React from 'react';
import {View,Text, TextInput, TouchableOpacity, StyleSheet} from 'react-native';
import {createStackNavigator} from 'react-navigation';
const fetch_url = 'http://192.168.0.17:8000/api/api-auth/';
export default class LoginForm extends React.Component {
constructor(props){
super(props);
this.loginHTTPRequest = this.loginHTTPRequest.bind(this);
this.state = {
username: '',
password:'',
respons:'',
error:null,
loading: false,
}
}
loginHTTPRequest(){
if(this.state.username != '' && this.state.password != ''){
this.setState({
loading:true,
});
fetch(fetch_url,{
method:'POST',
headers:{
Accept:'application/json',
'Content-Type':'application/json',
},
body: JSON.stringify({
username:'admin',
password:'admin12345',
}),
})
.then((response)=>{
if (response.status >= 200 && response.status < 300) {
//Where I want to extract the token from the response
console.log(response);
}})
.catch((error) => {
this.setState({
error:error,
loading:false,
});
});
}
}
render(){
return (
<View style={styles.container}>
<TextInput
style={styles.input}
autoCapitalize = 'none'
autoCorrect={false}
returnKeyType='next'
placeholder = 'Username'
onChangeText={(text)=> this.setState({username:text})}
/>
<TextInput
style={styles.input}
autoCapitalize = 'none'
autoCorrect={false}
returnKeyType='go'
placeholder = 'Password'
secureTextEntry
onChangeText={(text)=> this.setState({password:text})}
/>
<TouchableOpacity
style={styles.buttonContainer}
onPress={this.loginHTTPRequest}
>
<Text
style={styles.buttonText}
>
LOGIN
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 10,
},
input: {
height:60,
backgroundColor: '#d1d1d1',
color: 'black',
marginBottom: 10,
padding: 10,
},
buttonContainer:{
backgroundColor:'#F9CF00',
paddingVertical: 15,
},
buttonText:{
color: 'black',
textAlign: 'center',
fontWeight: '700',
marginBottom:20,
}
});