将Axios方法转换为Fetch

uidvcgyl  于 2023-08-04  发布在  iOS
关注(0)|答案(2)|浏览(154)

我很难找到一种方法来翻译下面的方法写的Axios获取。

import axios from 'axios';

const url = 'http://localhost:5000/api/posts/';

字符串
该URL正在使用'npm run dev'从我的服务器的端口5000运行

class PostService {

//Get Posts
static getPosts() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await axios.get(url);
            const data = res.data;
            resolve(
                data.map(post => ({
                    ...post,
                    createdAt: new Date(post.createdAt)
                }))
            );
        } catch (err) {
            reject(err);
        }
    })
}


上面是使用promise和axios来Map数据

//Create Posts
static insertPost(text, topic, price, location, provider, review) {
    return axios.post(url, {
        text,
        topic,
        price,
        location,
        provider,
        review
    });
}


上面是使用axios返回数据

//Delete Posts
static deletePost(id) {
    return axios.delete(`${url}${id}`);
}

}


上面是查找DB条目的ID并使用axios删除它。

export default PostService;

mefy6pfw

mefy6pfw1#

先做重要的事!第一个讨厌的是什么?
无论是承诺

static getPosts() {
  const turnCreatedAtToDate = post => ({
    ...post,
    createdAt: new Date(post.createdAt)
  });

  return axios.get(url)
              .then(data => data.map(turnCreatedAtToDate));
}

字符串
或完全异步

static async getPosts() {
  const data = await axios.get(url);
  return data.map(post => ({
    ...post,
    createdAt: new Date(post.createdAt)
  }));
}


但是不要收集所有的反模式,把它们放在一个碗里,疯狂地搅拌,然后倒入一个函数中。

返回主题

fetch有点冗长:

class PostService {
  //Get Posts
  static async getPosts() {
    const response = await fetch(url);
    const data = await response.json();

    return data.map(post => ({
      ...post,
      createdAt: new Date(post.createdAt)
    }));
  }

  //Create Posts
  static insertPost(text, topic, price, location, provider, review) {
    return fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(text,
        topic,
        price,
        location,
        provider,
        review
      })
    );
  }

  //Delete Posts
  static deletePost(id) {
    return fetch(`${url}${id}`, {
      method: "DELETE"
    });
  }
}

tsm1rwdh

tsm1rwdh2#

Fetch与axios非常相似,因此转换并没有那么不同:
JSON响应的一般方法:

try {
    const url = 'http://localhost:5000/api/posts/';
    const response = await fetch(url);
    const jsonData = await response.json();

    console.log(jsonData); // Do whatever you want with the JSON response...
  } catch (error) {
    console.error(error)
  }

字符串
如果我们会申请你的功能应该是这样的:

//Get Posts
static getPosts() {
    return new Promise(async (resolve, reject) => {
        try {
             const url = 'http://localhost:5000/api/posts/';
             const response = await fetch(url);
             const data = await response.json();

             resolve(
                data.map(post => ({
                    ...post,
                    createdAt: new Date(post.createdAt)
                }))
            );
        } catch (err) {
            reject(err);
        }
    })
}


现在来看看这篇文章:

//Create Posts
static insertPost(text, topic, price, location, provider, review) {

    const formData = new FormData()
    formData.append('text', text);
    formData.append('price', price);
    formData.append('location', location);
    formData.append('provider', provider);
    formData.append('review', review);

    try {
        const response = await fetch(url, { method: 'POST', body: formData });
        const jsonResponse = await response.json();

        return jsonResponse;
    } catch (error) {
        console.error(error)
    }
}


而对于删除

//Delete Posts
static deletePost(id) {
    return fetch(`${url}${id}, {method: "DELETE" });
}

相关问题