How can I send form data with React Native and Axios?

Viewed 3641

My code is simple. I have to send form data to the server. My token is also working. But I can't send the form data as data. It should be: "input": "message", but that gives me something very complicated. My Axios seems okay too, but I'm not sure.

const Screen = ({ navigation }) => {
  const [formData, setFormData] = useState();    
    
  const onSubmit = async ({ formData }) => {
    let token = await AsyncStorage.getItem("token");
    const data = new FormData();
    data.append("input", { input: formData });

    axios
      .post(
        `http://example.com/api`,
        (data: data),
        {
          crossdomain: true,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Credentials": "true",
          },
        }
      )
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <View>
        <Input
          value={formData}
          onChangeText={setFormData}
          placeholder="Type something"
          onSubmitEditing={() => onSubmit({ formData })}
        />
    </View>
  );
};

export default Screen;

In form-data part, my key is "input", my value is what the user wrote. So it's like: "input": "user's message". - But it gives the data like this:

FormData {
  "_parts": Array [
    Array [
      "input",
      Object {
        "input": "Naber",
      },
    ],
  ],
}
1 Answers

to append to formData like this :

data.append("input",formData);

and you need to send headers Content-Type as multipart/form-data and send the formData with axios like this:

axios.post("api",data,{
      headers: {
            Authorization: `Bearer ${token}`,
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Credentials": "true",
          }
})

if you are sending authorization header with each request you can attached to all axios req header with `axios.defaults.headers.common like this:

axios.defaults.headers.common['Authorization'] =`Bearer ${token}`;
Related