fetch基本方法的调用

2025年02月17日 建站教程

fetch​基本方法怎么使用,下面web建站小编给大家详细介绍一下!

fetch方法的设置

function formatParams(url, data) {
  return `${url}?${Object.keys(data)
    .map((e) => {
      if (data[e] !== "" && data[e] !== null && data[e] !== undefined) {
        return `${e}=${data[e]}`;
      } else {
        return null;
      }
    })
    .filter((e) => {
      return e;
    })
    .join("&")}`;
}

const data = { username: 'admin' };
const url = formatParams('https://lmcjl.com/profile',data)

fetch(url, {
  method: 'GET',
  //body: JSON.stringify(data), //get请求不能传body
})
.then(response => response.json())
.then(data => {
  console.log('success:', data);
})
.catch((error) => {
  console.error('error:', error);
});

post/put调用

const data = { username: 'admin' };

fetch('https://lmcjl.com/profile', {
  method: 'POST',
  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);
});

FormDate格式

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

formData.append('username', 'admin');
formData.append('avatar', fileField.files[0]);

fetch('https://lmcjl.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.then(result => {
  console.log('success:', result);
})
.catch(error => {
  console.error('error:', error);
});

本文链接:http://so.lmcjl.com/news/23331/

展开阅读全文
相关内容