Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you express it using the fetch API in JavaScript?

Now, I POST image data using ajax(jquery) as follows. The image is a File object.

async function postImage({ image }) {
  const result = await $.ajax({
    method: 'POST',
    url: '/api/images',
    dataType: 'json',
    data: image,
    processData: false,
    async: true,
    headers: {
      'Content-Type': 'application/octet-stream',
    },
  });
  return result;
}

The result that return object is {id: imageID}. How can I express this using the Fetch API? I couldn't get the result even if I did the following.

const result = await fetch('/api/images', {
    method: 'POST',
    body: image,
    headers: {
      'Content-Type': 'application/octet-stream',
    },
  });
return result;
like image 590
wato9902 Avatar asked Sep 15 '25 15:09

wato9902


1 Answers

fetch() returns a promise to a Response object, and that has a json() method which returns another promise to the parsed response JSON.

const response = await fetch('/api/images', {
  method: 'POST',
  body: image,
  headers: {
    'Content-Type': 'application/octet-stream',
  },
});
const result = await response.json();
like image 149
Patrick Roberts Avatar answered Sep 18 '25 06:09

Patrick Roberts