我是本机反应的新手,我想可能会错过一些非常简单的内容,但是我阅读了许多以前的问题,但没有得到答案。我正在尝试使用我的数据来获取POST请求,以便可以在获取功能之前在控制台中呈现或打印数据,但是当它发送数据时,它在服务器上为null。如果我尝试将硬核值直接用于提取功能,则效果很好。
export default class CreateNewPostScreen extends React.Component {
constructor(props){
super(props)
this.state = {
source: '',
description: '',
location: '',
token: ''
}
}
static navigationOptions = {
title: 'Create New Post'
}
componentWillMount() {
AsyncStorage.getItem("userToken").then((value) => {
this.setState({
//Getting data from prev screen(ProfileScreen)
source: this.props.navigation.state.params.newPostBase64Image,
token: value
})
}).done()
}
_fetchCreateNewPost = async () => {
fetch(baseUrl + 'api/profile/CreateNewPost',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
Authorization: this.state.token
},
body: JSON.stringify({
Date: new Date(),
Description: this.state.description,
Location: this.state.location,
SourcePath: this.state.source
}),
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
render() {
return(
<ScrollView style={{backgroundColor: 'white'}}>
<View style={styles.agreementField}>
<View>
<TouchableOpacity>
<Text style={styles.escBtn} onPress={() => this.props.navigation.navigate('Profile')}>X</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={this._fetchCreateNewPost}>
<Text style={styles.acceptBtn}>✓</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.container}>
<View style={{padding:5}}>
<Image
style={styles.image}
source={{uri:`data:image/png;base64,${this.state.source}`}}
/>
</View>
<View style={styles.textAreaContainer} >
<TextInput
style={styles.textArea}
underlineColorAndroid="transparent"
placeholder="Type something"
placeholderTextColor="grey"
numberOfLines={1}
multiline={true}
onChangeText={(text) => this.setState({description:text})}
/>
</View>
</View>
<View>
<View>
<TextInput
style={styles.input}
placeholder="Location"
underlineColorAndroid= '#C0C0C0'
onChangeText={(text) => this.setState({location:text})}
/>
</View>
</View>
</ScrollView>
)
}
}
答案 0 :(得分:0)
主体必须是JSON,而不是字符串。 JSON.stringify()返回一个字符串。
我认为您必须将代码更改为此(我更改了一些其他内容):
您的_fetchCreateNewPost
函数:
_fetchCreateNewPost = () => {
return fetch(baseUrl + 'api/profile/CreateNewPost',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
Authorization: this.state.token
},
body: {
Date: new Date(),
Description: this.state.description,
Location: this.state.location,
SourcePath: this.state.source
},
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch((error) => {
console.log(error)
})
}
使用onPress
的{{1}}中的 TouchableOpacity
:
_fetchCreateNewPost