Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

415 Unsupported media type using axios post request in react js

I am trying to post an image with some other information through a react form but when I send the request it does not support the type of image file. From postman to my django server it works perfectly but when I try to make post request through react it gives 415 Unsupported media type in dev tools console.

This is the react code

const navigate = useNavigate();
  const initialFormData = Object.freeze({
    title: "",
    place: "",
    slug: "",
    description: "",
  });

  const [postData, updateFormData] = useState(initialFormData);
  const [postimage, setPostImage] = useState(null);

  const handleChange = (e) => {
      if ([e.target.name] == 'image') {
          setPostImage({
              image: e.target.files,
          });
          console.log(e.target.files);
      }
      if ([e.target.name] == 'title') {
          updateFormData({
              ...postData,
              [e.target.name]: e.target.value.trim(),
              ['slug']: slugify(e.target.value.trim()),
          });
      } else {
          updateFormData({
              ...postData,
              [e.target.name]: e.target.value.trim(),
          });
      }
  };

  const handleSubmit = (e) => {
      e.preventDefault();
      let formData = new FormData();
      formData.append('title', postData.title);
      formData.append('slug', postData.slug);
      formData.append('author', 10);
      formData.append('description', postData.description);
      formData.append('place', postData.place);
      formData.append('job_date','2022-04-03')
      formData.append('image', postimage.image[0]);

      axiosInstance.post(`admin/create/`, formData);
      navigate({
          pathname: '/admin/',
      });
      window.location.reload();

    console.log(postimage.image[0])
  };

  return (
    <Container component="main" maxWidth="xs">
      <div>
        <Typography component="h1" variant="h5">
          Create New Post
        </Typography>
        <form noValidate>
          <Grid container spacing={2}>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="title"
                label="Post Title"
                name="title"
                autoComplete="title"
                onChange={handleChange}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="place"
                label="Job Location:"
                name="place"
                autoComplete="location"
                onChange={handleChange}
              />
            </Grid>
            <Grid item xs={12}>
              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <DatePicker />
              </LocalizationProvider>
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="description"
                label="Description"
                name="description"
                autoComplete="description"
                onChange={handleChange}
                multiline
                rows={4}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                variant="outlined"
                required
                fullWidth
                id="slug"
                label="slug"
                name="slug"
                autoComplete="slug"
                value={postData.slug}
                onChange={handleChange}
              />
            </Grid>
            <Grid item xs={12}>
              <input
                accept="image/png, image/gif, image/jpeg"
                id="image"
                onChange={handleChange}
                name="image"
                type="file"
              />
            </Grid>
            <Grid item xs={12}>
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            onClick={handleSubmit}
          >
            Create Post
          </Button>
            </Grid>
          </Grid>

         
         
        </form>
      </div>
    </Container>
  );
}

Axios request looks like this with the responsive header:


const axiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
            ? 'JWT ' + localStorage.getItem('access_token')
            : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    }, 
});

enter image description here

like image 456
User G Amsterdam Avatar asked Oct 20 '25 00:10

User G Amsterdam


1 Answers

As you are uploading the file. You can't use Content-Type: application/json. You must use Content-Type: multipart/form-data. You can achieve this with the following axios example.

var formData = new FormData();
formData.append("image", imagefile);
formData.append("title", "test");
formData.append("slug", "test");
axios.post(baseURL, formData, {
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
            ? 'JWT ' + localStorage.getItem('access_token')
            : null,
        'Content-Type': 'multipart/form-data'
        accept: 'application/json', // If you receieve JSON response.
    }
})
like image 107
Dhaval Gajjar Avatar answered Oct 21 '25 14:10

Dhaval Gajjar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!