如何在 axios, React Native 中设置 headers

How to set headers in axios, ReactNative

我构建了一个应用程序,React Native 作为前端,Django 作为后端, 我使用 axios 从用户那里获取数据然后将其发送到后端它显示错误请求失败,状态代码为 400

我在本地使用了 Restful API 构建的 django 和 运行 服务器, 所以我认为当我将 headers 添加到 axios 时 API 请求响应没有错误

那么,如何在axios中设置headers

用户通过表单输入数据并发送到后台

Add.js 带有表单的页面从用户那里获取数据并将其发送到后端

 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;

您可以传递第三个参数的选项。您可以在 post 方法上添加 headers,如下所示:

axios.post('https://example.com', formData, { headers: 'content-type': 'text/json',...otherHeaders })

您必须传递一个带有 headers 的对象,如文档所述:https://axios-http.com/docs/req_config

因此您的请求将是:

axios.post('http://192.168.8.143:8000/transactions/',{formData}, {
   //example with bearer token
   headers: {
     'Authentication': 'Bearer 89324u2jhjwe98'
   }
})
.then(function (response) {
   console.log(response);
})
.catch(function (error) {
    console.log(error);
});