【发布时间】:2018-08-16 02:37:55
【问题描述】:
我正在开发一个带有原生反应的移动应用程序。我对此很陌生,我无法弄清楚如何发出正确的 POST HTTP 请求以将数据发送到 API。我得到了以下示例:
POST /devapi/records/?access_token=[...] HTTP/1.1
主机:website.org
内容类型:application/x-www-form-urlencoded
units=12331&title=test&date=07/10/2018&requirementId=3&isInternal=1&serviceType=campus
成功的样子:
{
"recordId": 63, “单位”:2, “名称”:“鲍勃”, “成功”:是的
}
错误看起来像:
{
"message": "您必须为此记录输入日期。", “错误”:-2
}
我目前的解决方案如下:
postRecord() {
const input = {
units: this.state.units,
title: this.state.title,
date: this.convertToUnix(this.state.date),
requirementId: this.props.navigation.state.params.requirementId,
isInternal: this.state.differentiateExternal,
serviceType: this.state.type
};
const params = this.props.screenProps.navigation.state.params;
const accessToken = params ? params.currstate.accessToken : null;
const searchParams = Object.keys(input).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(input[key])}`).join('&');
console.log('searchParams', searchParams);
return fetch('https://webiste.org/devapi/records/?access_token=' + accessToken=[...] HTTP/1.1, {
method: 'POST',
header: {
'Content-length': '86',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: input.units + input.title + input.date + input.requirementId + input.isInternal + input.serviceType
})
.then((response) => response.json())
.then((responseJson) => {
console.log('the response is:', responseJson);
if (responseJson.success === 'true') {
Alert.alert(
'Record created successfully',
[
{
text: 'Ok',
style: 'cancel',
onPress: () => this.props.navigation.navigate('RequirementRecordScreen')
}
]
);
} else if (responseJson.error === -2) {
Alert.alert(
'There was an error creating the record',
responseJson.message,
[
{
text: 'Ok',
style: 'cancel',
onPress: () => console.log('Cancel xDDDD')
}
],
);
}
});
}
在测试运行时,我的 console.log() 返回:
searchParams units=3&title=test%20test%20test&date=1534402800&requirementId=3&isInternal=0&serviceType=nation
然后总是返回一个 JSON 响应错误,指出我需要输入多个“单位”。如何修改它以使其正常工作?
【问题讨论】:
-
您应该联系后端团队。也许您使用了错误的日期参数
标签: json react-native post httprequest