wato9902
wato9902

Reputation: 659

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;

Upvotes: 3

Views: 3004

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51756

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();

Upvotes: 4

Related Questions