get和post请求fetchData.js

2018-10-21  本文已影响0人  __MX

//在util包下新建fetchData.js

const baseURL = "https://cnodejs.org/api/v1";

//封装的GET请求

export const getData = async (url, data) => {

  let api = baseURL + url + "?";

  if (data) {

    for (key in data) {

      api += key + "=" + data[key] + "&";

    }

  }

  api = api.substr(0, api.length - 1);

  let res = await fetch(api);

  res = await res.json();

  return res;

};

//通过post获取数据,url是接口地址,obj是发送给后台的数据对象

export const postData = async (url, obj) => {

  let res = await fetch(baseURL + url, {

    method: "POST",

    headers: {

      Accept: "application/json",

      "Content-Type": "application/json"

    },

    body: JSON.stringify(obj)

  });

  let json = await res.json();

  return json;

};

上一篇 下一篇

猜你喜欢

热点阅读