简体   繁体   中英

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;

fetch() returns a promise to aResponse 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM