1

Всем привет!

как на JS сделать обертку для fetch на js?

чтобы работало:

fetch.put, fetch. post

означая что метод put и post соответственно

спасибо

1
  • Попробуйте через prototype. Fetch.prototype.put=function(){ }
    – axmed2004
    6 июн 2020 в 6:28

1 ответ 1

2

fetch.put = createFetchWrapper("PUT");
fetch.get = createFetchWrapper("GET");
fetch.post = createFetchWrapper("POST");

// Get запрос
fetch.get("https://reqres.in/api/users?page=1")
  .then(res => res.json())
  .then(console.log);

// Post запрос
fetch.post("https://reqres.in/api/users", {cors: "no-cors"})
  .then(res => res.json())
  .then(console.log);
 
// PUT запрос несмотря на переданный параметр method в объекте настроек
fetch.put("https://reqres.in/api/users", { method: "GET" })
  .then(res => res.json())
  .then(console.log);


function createFetchWrapper(method) { 
  const defaultOptions = { method };
  return function wrapper(url, options) {
    options || (options = {});
    return fetch(url, Object.assign(options, defaultOptions));
  }
}

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.