Hướng dẫn fetch api post form data javascript - tìm nạp api dữ liệu biểu mẫu bài đăng javascript

API tìm nạp cung cấp giao diện JavaScript để truy cập và thao tác các phần của giao thức, chẳng hạn như yêu cầu và phản hồi. Nó cũng cung cấp một phương thức

fetch['//example.com', {
  credentials: 'include'
}];
0 toàn cầu cung cấp một cách dễ dàng, hợp lý để tìm nạp tài nguyên không đồng bộ trên mạng.

Loại chức năng này trước đây đã đạt được bằng cách sử dụng

fetch['//example.com', {
  credentials: 'include'
}];
1. Fetch cung cấp một giải pháp thay thế tốt hơn có thể dễ dàng sử dụng bởi các công nghệ khác như
fetch['//example.com', {
  credentials: 'include'
}];
2. Fetch cũng cung cấp một nơi logic duy nhất để xác định các khái niệm liên quan đến HTTP khác như CORS và phần mở rộng cho HTTP.

Thông số kỹ thuật

fetch['//example.com', {
  credentials: 'include'
}];
3 khác với
fetch['//example.com', {
  credentials: 'include'
}];
4 theo những cách quan trọng sau:

  • Lời hứa được trả lại từ
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    0 sẽ không từ chối trạng thái lỗi HTTP ngay cả khi phản hồi là HTTP 404 hoặc 500. Thay vào đó, ngay khi máy chủ phản hồi với các tiêu đề, lời hứa sẽ giải quyết bình thường [với thuộc tính
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    6 của phản hồi được đặt thành Sai nếu phản hồi không trong phạm vi 200 trận299] và nó sẽ chỉ từ chối về lỗi mạng hoặc nếu mọi thứ ngăn yêu cầu hoàn thành.won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally [with the
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    6 property of the response set to false if the response isn't in the range 200–299], and it will only reject on network failure or if anything prevented the request from completing.
  • Trừ khi
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    0 được gọi với tùy chọn
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    8 được đặt thành
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    9,
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    0:
    • Sẽ không gửi cookie trong các yêu cầu có nguồn gốc chéo
    • sẽ không đặt bất kỳ cookie nào được gửi lại trong các phản hồi có nguồn gốc chéo
    • Kể từ tháng 8 năm 2018, chính sách thông tin đăng nhập mặc định đã thay đổi thành cùng với nguồn gốc. Firefox cũng được sửa đổi trong phiên bản 61.0b13]

Một yêu cầu tìm nạp cơ bản thực sự đơn giản để thiết lập. Hãy xem mã sau:

fetch['//example.com/movies.json']
  .then[[response] => response.json[]]
  .then[[data] => console.log[data]];

Ở đây chúng tôi đang tìm nạp một tệp JSON trên mạng và in nó vào bảng điều khiển. Việc sử dụng đơn giản nhất

fetch['//example.com', {
  credentials: 'include'
}];
0 có một đối số - đường dẫn đến tài nguyên bạn muốn tìm nạp - và không trực tiếp trả về phần thân phản hồi JSON mà thay vào đó trả về một lời hứa giải quyết với đối tượng
// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
2.

Lần lượt, đối tượng

// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
2 không chứa trực tiếp phần thân phản hồi JSON thực tế mà thay vào đó là biểu diễn của toàn bộ phản hồi HTTP. Vì vậy, để trích xuất nội dung cơ thể JSON từ đối tượng
// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
2, chúng tôi sử dụng phương pháp
// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
5, trả về lời hứa thứ hai giải quyết với kết quả phân tích văn bản cơ thể phản hồi là JSON.

Lưu ý: Xem phần cơ thể cho các phương pháp tương tự để trích xuất các loại nội dung cơ thể khác. See the Body section for similar methods to extract other types of body content.

Các yêu cầu tìm nạp được kiểm soát bởi chỉ thị của chính sách bảo mật nội dung

// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
6 thay vì chỉ thị của các tài nguyên mà nó đang truy xuất.

Cung cấp các tùy chọn yêu cầu

Phương thức

fetch['//example.com', {
  credentials: 'include'
}];
0 có thể tùy ý chấp nhận tham số thứ hai, đối tượng
// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
8 cho phép bạn kiểm soát một số cài đặt khác nhau:

Xem

fetch['//example.com', {
  credentials: 'include'
}];
0 để biết các tùy chọn đầy đủ có sẵn, và nhiều chi tiết hơn.

// Example POST method implementation:
async function postData[url = '', data = {}] {
  // Default options are marked with *
  const response = await fetch[url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify[data] // body data type must match "Content-Type" header
  }];
  return response.json[]; // parses JSON response into native JavaScript objects
}

postData['//example.com/answer', { answer: 42 }]
  .then[[data] => {
    console.log[data]; // JSON data parsed by `data.json[]` call
  }];

Lưu ý rằng

fetch['//example.com', {
  credentials: 'omit'
}]
0 chỉ cho phép một bộ tiêu đề giới hạn trong yêu cầu:

  • fetch['//example.com', {
      credentials: 'omit'
    }]
    
    1
  • fetch['//example.com', {
      credentials: 'omit'
    }]
    
    2
  • fetch['//example.com', {
      credentials: 'omit'
    }]
    
    3
  • fetch['//example.com', {
      credentials: 'omit'
    }]
    
    4 với giá trị
    fetch['//example.com', {
      credentials: 'omit'
    }]
    
    5,
    fetch['//example.com', {
      credentials: 'omit'
    }]
    
    6 hoặc
    fetch['//example.com', {
      credentials: 'omit'
    }]
    
    7

Gửi yêu cầu với thông tin đăng nhập bao gồm

Để khiến các trình duyệt gửi yêu cầu với thông tin đăng nhập được bao gồm trên cả các cuộc gọi đồng nghĩa và nguồn gốc chéo, hãy thêm

fetch['//example.com', {
  credentials: 'omit'
}]
8 vào đối tượng
// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];
8 bạn chuyển sang phương thức
fetch['//example.com', {
  credentials: 'include'
}];
0.

fetch['//example.com', {
  credentials: 'include'
}];

Lưu ý:

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
1 bị cấm sử dụng ký tự đại diện cho các yêu cầu với
fetch['//example.com', {
  credentials: 'omit'
}]
8. Trong những trường hợp như vậy, nguồn gốc chính xác phải được cung cấp; Ngay cả khi bạn đang sử dụng tiện ích mở rộng CORS Unblocker, các yêu cầu vẫn sẽ thất bại.
const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
1 is prohibited from using a wildcard for requests with
fetch['//example.com', {
  credentials: 'omit'
}]
8. In such cases, the exact origin must be provided; even if you are using a CORS unblocker extension, the requests will still fail.

Lưu ý: Trình duyệt không nên gửi thông tin đăng nhập trong các yêu cầu trước không phân biệt cài đặt này. Để biết thêm thông tin, xem: CORS> Yêu cầu có thông tin đăng nhập. Browsers should not send credentials in preflight requests irrespective of this setting. For more information see: CORS > Requests with credentials.

Nếu bạn chỉ muốn gửi thông tin đăng nhập nếu URL yêu cầu có cùng nguồn gốc với tập lệnh gọi, hãy thêm

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
3.

// The calling script is on the origin '//example.com'

fetch['//example.com', {
  credentials: 'same-origin'
}];

Thay vào đó, đảm bảo các trình duyệt không bao gồm thông tin đăng nhập trong yêu cầu, hãy sử dụng

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
4.

fetch['//example.com', {
  credentials: 'omit'
}]

Tải dữ liệu JSON lên

Sử dụng

fetch['//example.com', {
  credentials: 'include'
}];
0 để đăng dữ liệu được mã hóa JSON.

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];

Tải lên một tập tin

Các tệp có thể được tải lên bằng phần tử nhập HTML

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
6,
const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
7 và
fetch['//example.com', {
  credentials: 'include'
}];
0.

const formData = new FormData[];
const fileField = document.querySelector['input[type="file"]'];

formData.append['username', 'abc123'];
formData.append['avatar', fileField.files[0]];

fetch['//example.com/profile/avatar', {
  method: 'PUT',
  body: formData
}]
  .then[[response] => response.json[]]
  .then[[result] => {
    console.log['Success:', result];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];

Tải lên nhiều tập tin

Các tệp có thể được tải lên bằng phần tử nhập HTML

const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
9,
const data = { username: 'example' };

fetch['//example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify[data],
}]
  .then[[response] => response.json[]]
  .then[[data] => {
    console.log['Success:', data];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];
7 và
fetch['//example.com', {
  credentials: 'include'
}];
0.

const formData = new FormData[];
const photos = document.querySelector['input[type="file"][multiple]'];

formData.append['title', 'My Vegas Vacation'];
let i = 0;
for [const photo of photos.files] {
  formData.append[`photos_${i}`, photo];
  i++;
}

fetch['//example.com/posts', {
  method: 'POST',
  body: formData,
}]
  .then[[response] => response.json[]]
  .then[[result] => {
    console.log['Success:', result];
  }]
  .catch[[error] => {
    console.error['Error:', error];
  }];

Xử lý một dòng tệp văn bản từng dòng

Các khối được đọc từ một phản hồi không bị phá vỡ gọn gàng ở ranh giới dòng và là uint8arrays, không phải chuỗi. Nếu bạn muốn tìm nạp một tệp văn bản và xử lý từng dòng, tùy thuộc vào bạn để xử lý các biến chứng này. Ví dụ sau đây cho thấy một cách để làm điều này bằng cách tạo một trình lặp dòng [để đơn giản, nó giả sử văn bản là UTF-8 và không xử lý các lỗi tìm nạp].

async function* makeTextFileLineIterator[fileURL] {
  const utf8Decoder = new TextDecoder['utf-8'];
  const response = await fetch[fileURL];
  const reader = response.body.getReader[];
  let { value: chunk, done: readerDone } = await reader.read[];
  chunk = chunk ? utf8Decoder.decode[chunk] : '';

  const re = /\n|\r|\r\n/gm;
  let startIndex = 0;
  let result;

  while [true] {
    let result = re.exec[chunk];
    if [!result] {
      if [readerDone] break;
      let remainder = chunk.substr[startIndex];
      [{ value: chunk, done: readerDone } = await reader.read[]];
      chunk = remainder + [chunk ? utf8Decoder.decode[chunk] : ''];
      startIndex = re.lastIndex = 0;
      continue;
    }
    yield chunk.substring[startIndex, result.index];
    startIndex = re.lastIndex;
  }

  if [startIndex  {
    if [!response.ok] {
      throw new Error['Network response was not OK'];
    }
    return response.blob[];
  }]
  .then[[myBlob] => {
    myImage.src = URL.createObjectURL[myBlob];
  }]
  .catch[[error] => {
    console.error['There has been a problem with your fetch operation:', error];
  }];
2 - Một số nguyên [giá trị mặc định 200] chứa mã trạng thái phản hồi.
  • fetch['flowers.jpg']
      .then[[response] => {
        if [!response.ok] {
          throw new Error['Network response was not OK'];
        }
        return response.blob[];
      }]
      .then[[myBlob] => {
        myImage.src = URL.createObjectURL[myBlob];
      }]
      .catch[[error] => {
        console.error['There has been a problem with your fetch operation:', error];
      }];
    
    3 - một chuỗi [giá trị mặc định ""], tương ứng với thông báo mã trạng thái HTTP. Lưu ý rằng HTTP/2 không hỗ trợ các thông báo trạng thái.
  • const formData = new FormData[];
    const fileField = document.querySelector['input[type="file"]'];
    
    formData.append['username', 'abc123'];
    formData.append['avatar', fileField.files[0]];
    
    fetch['//example.com/profile/avatar', {
      method: 'PUT',
      body: formData
    }]
      .then[[response] => response.json[]]
      .then[[result] => {
        console.log['Success:', result];
      }]
      .catch[[error] => {
        console.error['Error:', error];
      }];
    
    5-Được sử dụng ở trên, đây là tốc ký để kiểm tra xem trạng thái đó có trong phạm vi bao gồm 200-299. Điều này trả về một giá trị boolean.
  • Chúng cũng có thể được tạo theo chương trình thông qua JavaScript, nhưng điều này chỉ thực sự hữu ích trong

    const formData = new FormData[];
    const photos = document.querySelector['input[type="file"][multiple]'];
    
    formData.append['title', 'My Vegas Vacation'];
    let i = 0;
    for [const photo of photos.files] {
      formData.append[`photos_${i}`, photo];
      i++;
    }
    
    fetch['//example.com/posts', {
      method: 'POST',
      body: formData,
    }]
      .then[[response] => response.json[]]
      .then[[result] => {
        console.log['Success:', result];
      }]
      .catch[[error] => {
        console.error['Error:', error];
      }];
    
    5, khi bạn đang cung cấp phản hồi tùy chỉnh cho yêu cầu nhận được bằng phương thức
    fetch['flowers.jpg']
      .then[[response] => {
        if [!response.ok] {
          throw new Error['Network response was not OK'];
        }
        return response.blob[];
      }]
      .then[[myBlob] => {
        myImage.src = URL.createObjectURL[myBlob];
      }]
      .catch[[error] => {
        console.error['There has been a problem with your fetch operation:', error];
      }];
    
    6:

    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    7

    Chất xây dựng

    fetch['flowers.jpg']
      .then[[response] => {
        if [!response.ok] {
          throw new Error['Network response was not OK'];
        }
        return response.blob[];
      }]
      .then[[myBlob] => {
        myImage.src = URL.createObjectURL[myBlob];
      }]
      .catch[[error] => {
        console.error['There has been a problem with your fetch operation:', error];
      }];
    
    7 có hai đối số tùy chọn - một phần thân cho phản hồi và một đối tượng init [tương tự như
    const formData = new FormData[];
    const fileField = document.querySelector['input[type="file"]'];
    
    formData.append['username', 'abc123'];
    formData.append['avatar', fileField.files[0]];
    
    fetch['//example.com/profile/avatar', {
      method: 'PUT',
      body: formData
    }]
      .then[[response] => response.json[]]
      .then[[result] => {
        console.log['Success:', result];
      }]
      .catch[[error] => {
        console.error['Error:', error];
      }];
    
    7 chấp nhận.]

    Lưu ý: Phương thức tĩnh

    fetch['flowers.jpg']
      .then[[response] => {
        if [!response.ok] {
          throw new Error['Network response was not OK'];
        }
        return response.blob[];
      }]
      .then[[myBlob] => {
        myImage.src = URL.createObjectURL[myBlob];
      }]
      .catch[[error] => {
        console.error['There has been a problem with your fetch operation:', error];
      }];
    
    9 trả về phản hồi lỗi. Tương tự,
    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    00 trả về một phản hồi dẫn đến chuyển hướng đến một URL được chỉ định. Đây cũng chỉ liên quan đến nhân viên dịch vụ.
    The static method
    fetch['flowers.jpg']
      .then[[response] => {
        if [!response.ok] {
          throw new Error['Network response was not OK'];
        }
        return response.blob[];
      }]
      .then[[myBlob] => {
        myImage.src = URL.createObjectURL[myBlob];
      }]
      .catch[[error] => {
        console.error['There has been a problem with your fetch operation:', error];
      }];
    
    9 returns an error response. Similarly,
    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    00 returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.

    Thân hình

    Cả hai yêu cầu và phản hồi có thể chứa dữ liệu cơ thể. Một cơ thể là một ví dụ của bất kỳ loại nào sau đây:

    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      01
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      02 [Uint8array và bạn bè]
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      03
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      04
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      05
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      06, hoặc một chuỗi theo nghĩa đen
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      07
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      08

    Giao diện

    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    09 và
    // The calling script is on the origin '//example.com'
    
    fetch['//example.com', {
      credentials: 'same-origin'
    }];
    
    2 chia sẻ các phương pháp sau để trích xuất cơ thể. Tất cả đều trả lại một lời hứa cuối cùng được giải quyết với nội dung thực tế.

    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      11 /
      // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      12
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      13 /
      // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      14
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      15 /
      // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      16
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      17 /
      // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      18
    • // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      19 /
      // Example POST method implementation:
      async function postData[url = '', data = {}] {
        // Default options are marked with *
        const response = await fetch[url, {
          method: 'POST', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: 'same-origin', // include, *same-origin, omit
          headers: {
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify[data] // body data type must match "Content-Type" header
        }];
        return response.json[]; // parses JSON response into native JavaScript objects
      }
      
      postData['//example.com/answer', { answer: 42 }]
        .then[[data] => {
          console.log[data]; // JSON data parsed by `data.json[]` call
        }];
      
      20

    Điều này làm cho việc sử dụng dữ liệu phi văn bản dễ dàng hơn nhiều so với XHR.

    Các cơ quan yêu cầu có thể được đặt bằng cách truyền các tham số cơ thể:

    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    8

    Cả yêu cầu và phản hồi [và bằng cách mở rộng hàm

    fetch['//example.com', {
      credentials: 'include'
    }];
    
    0], sẽ cố gắng xác định thông minh loại nội dung. Yêu cầu cũng sẽ tự động đặt tiêu đề
    fetch['//example.com', {
      credentials: 'omit'
    }]
    
    4 nếu không có được đặt trong từ điển.

    Phát hiện tính năng

    Hỗ trợ API tìm nạp có thể được phát hiện bằng cách kiểm tra sự tồn tại của

    const formData = new FormData[];
    const photos = document.querySelector['input[type="file"][multiple]'];
    
    formData.append['title', 'My Vegas Vacation'];
    let i = 0;
    for [const photo of photos.files] {
      formData.append[`photos_${i}`, photo];
      i++;
    }
    
    fetch['//example.com/posts', {
      method: 'POST',
      body: formData,
    }]
      .then[[response] => response.json[]]
      .then[[result] => {
        console.log['Success:', result];
      }]
      .catch[[error] => {
        console.error['Error:', error];
      }];
    
    3,
    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    09,
    // The calling script is on the origin '//example.com'
    
    fetch['//example.com', {
      credentials: 'same-origin'
    }];
    
    2 hoặc
    fetch['//example.com', {
      credentials: 'include'
    }];
    
    0 trên phạm vi
    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    27 hoặc
    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    28. Ví dụ:

    // Example POST method implementation:
    async function postData[url = '', data = {}] {
      // Default options are marked with *
      const response = await fetch[url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify[data] // body data type must match "Content-Type" header
      }];
      return response.json[]; // parses JSON response into native JavaScript objects
    }
    
    postData['//example.com/answer', { answer: 42 }]
      .then[[data] => {
        console.log[data]; // JSON data parsed by `data.json[]` call
      }];
    
    9

    Thông số kỹ thuật

    Sự chỉ rõ
    Tìm nạp tiêu chuẩn # Fetch-method
    # fetch-method

    Tính tương thích của trình duyệt web

    Bảng BCD chỉ tải trong trình duyệt

    Xem thêm

    Làm cách nào để sử dụng API tìm nạp để đăng dữ liệu?

    Yêu cầu đăng bằng API tìm nạp: Để thực hiện yêu cầu POST Chúng tôi cần chỉ định các tham số bổ sung với yêu cầu như phương thức, tiêu đề, v.v. . Sau đó, nó sẽ trả về cùng một nội dung bài viết bằng một ID.To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.

    Có thể tìm nạp API được sử dụng cho bài đăng?

    API tìm nạp đi kèm với phương thức Fetch [] cho phép bạn tìm nạp dữ liệu từ tất cả các địa điểm khác nhau và làm việc với dữ liệu được tìm nạp.Nó cho phép bạn thực hiện yêu cầu HTTP, tức là, yêu cầu GET [để nhận dữ liệu] hoặc yêu cầu đăng [cho dữ liệu đăng].POST request [for posting data].

    Làm thế nào lấy dữ liệu tìm nạp từ JavaScript?

    Phương thức serializeArray [] tạo ra một mảng các đối tượng [tên và giá trị] bằng cách nối tiếp các giá trị biểu mẫu.Phương pháp này có thể được sử dụng để có được dữ liệu biểu mẫu.Tham số: Nó không chấp nhận bất kỳ tham số nào.Giá trị trả về: Nó trả về tất cả các giá trị bên trong các trường đầu vào.. This method can be used to get the form data. Parameter: It does not accept any parameter. Return Value: It returns all the value that is inside the inputs fields.

    Làm thế nào để bạn thực hiện một cuộc gọi API bài đăng trong JavaScript?

    Chuyển dữ liệu cho yêu cầu POST // Dữ liệu được gửi đến yêu cầu POST LET _DATA = {Tiêu đề: "Foo", Body: "Bar", UserID: 1} Fetch ['//jsonplaceholder.typicode.com/posts', {Phương thức: "Post", Body: Json. Stringify [_Data], tiêu đề: {"loại nội dung": "application/json; charaTeSt = utf-8"}}].Sau đó [Phản hồi => Phản hồi.

    Bài Viết Liên Quan

    Chủ Đề