我试图构建一个财务管理应用程序,React Native作为前端,Django作为后端,我使用axios从用户那里获取数据,然后将其发送到后端,它显示错误请求失败,状态码为400
用户通过表单输入数据并将其发送到后端,我使用了用django构建的RestfulAPI并在本地运行服务器
import * as React from "react";
import {View, Text, Image, StyleSheet, Button, TextInput} from "react-native";
import { COLORS, SIZES,FONTS} from '../styles/theme.js';
import { FieldArray, Formik} from "formik";
import axios from 'axios';
const AddScreen =()=>{
const radioopt = [{},{},{},{}];
const submit = (val) => {
if(val.type == "" || val.category == "" || val.amount == ""){
alert("Please Enter all details");
return;
}
// 'http://192.168.8.143:8000/transactions/'
axios.post('http://192.168.8.143:8000/transactions/', {
"id": "1",
"type": val?.type,
"category": val.category,
"amount": val?.amount,
// "owner" : "",
"date" : Date.now(),
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
return(
<View style={{flex: 1, backgroundColor:COLORS.gray}}>
<Formik
initialValues={{type:'',category:'', amount:''}}
onSubmit={(values)=>{submit(values)}}
>
{(props)=>(
<View style={styles.whitecard}>
<TextInput
style={styles.inputstyle}
placeholder='type'
onChangeText={props.handleChange('type')}
value={props.values.type}
/>
<TextInput
style={styles.inputstyle}
placeholder='category'
onChangeText={props.handleChange('category')}
value={props.values.category}
/>
<TextInput
style={styles.inputstyle}
placeholder='amount'
onChangeText={props.handleChange('amount')}
value={props.values.amount}
keyboardType='numeric'
/>
<View style={{margin:10,padding:0, backgroundColor:COLORS.pink, borderRadius:6}}>
<Button title='Submit' color='white' onPress={props.handleSubmit}></Button>
</View>
</View>
)}
</Formik>
</View>
);
}
...
export default AddScreen;
我尝试我的代码与假API和它的工作,请让我知道,如果错误引起的后端。
你是否允许HTTP的android和ios请求?允许HTTP请求如下。
对于Android:将以下属性添加到您的AndroidManifest. xml
<manifest
//..... rest code
<application
android:usesCleartextTraffic="true">
// ----------------
</application>
</manifest>
为了IOS,如果你想让一切都写这里面info. plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
对于博览会IOS编辑您的app. json和app.json-
"ios": {
"supportsTablet": true,
"infoPlist": {
"NSAppTransportSecurity" : {
"NSAllowsArbitraryLoads" : true,
}
}
}