最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - 415 Unsupported media type using axios post request in react js - Stack Overflow

programmeradmin1浏览0评论

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 ponent="main" maxWidth="xs">
      <div>
        <Typography ponent="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',
    }, 
});

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 ponent="main" maxWidth="xs">
      <div>
        <Typography ponent="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',
    }, 
});

Share Improve this question edited Mar 8, 2023 at 14:21 Christian Baumann 3,5924 gold badges24 silver badges45 bronze badges asked Mar 8, 2023 at 13:10 User G AmsterdamUser G Amsterdam 671 silver badge10 bronze badges 2
  • 1 You can not perform a file upload with Content-Type: application/json. – C3roe Commented Mar 8, 2023 at 13:13
  • if ([e.target.name] == '…') looks like a mistake, why would you pare an array to a string? Also you should not window.location.reload() if you already navigate(…), and certainly you should not do it without waiting for the request to suceed! – Bergi Commented Mar 8, 2023 at 13:31
Add a ment  | 

1 Answer 1

Reset to default 4

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.
    }
})
发布评论

评论列表(0)

  1. 暂无评论