原生js怎么用fetch发请求

原生js怎么用fetch发请求

原生JS如何使用fetch发送请求

使用原生JavaScript的fetch API发送请求的核心步骤包括:创建请求、处理响应、捕获错误。我们将详细描述如何使用fetch API来发送GET和POST请求,并处理响应数据。

一、FETCH API简介

fetch API是现代JavaScript中用于发送网络请求的原生方法,它取代了旧的XMLHttpRequest。fetch提供了更简洁、更强大的方式来与服务器进行交互。

1、基础使用

使用fetch API发送请求非常简单,它返回一个Promise对象,可以链式处理响应。

fetch('https://api.example.com/data')

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

2、GET请求

GET请求是最常见的HTTP请求方法,用于从服务器获取数据。

fetch('https://api.example.com/data')

.then(response => response.json())

.then(data => {

console.log(data); // 处理响应数据

})

.catch(error => {

console.error('Error:', error); // 处理错误

});

3、POST请求

POST请求用于向服务器发送数据,通常用于提交表单数据或上传文件。

fetch('https://api.example.com/data', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({

name: 'John Doe',

age: 30

})

})

.then(response => response.json())

.then(data => {

console.log(data); // 处理响应数据

})

.catch(error => {

console.error('Error:', error); // 处理错误

});

二、FETCH API高级用法

1、处理不同类型的响应数据

fetch API可以处理多种类型的响应数据,包括JSON、文本、Blob等。

JSON数据

fetch('https://api.example.com/data')

.then(response => response.json())

.then(data => console.log(data));

文本数据

fetch('https://api.example.com/data')

.then(response => response.text())

.then(text => console.log(text));

Blob数据

fetch('https://api.example.com/image')

.then(response => response.blob())

.then(blob => {

const img = document.createElement('img');

img.src = URL.createObjectURL(blob);

document.body.appendChild(img);

});

2、处理HTTP错误

fetch API不会自动抛出HTTP错误(如404或500),需要手动检查响应的状态码。

fetch('https://api.example.com/data')

.then(response => {

if (!response.ok) {

throw new Error('Network response was not ok ' + response.statusText);

}

return response.json();

})

.then(data => console.log(data))

.catch(error => console.error('There has been a problem with your fetch operation:', error));

3、设置请求头

在某些情况下,需要设置自定义请求头,例如在发送带有身份验证的请求时。

fetch('https://api.example.com/data', {

method: 'GET',

headers: {

'Authorization': 'Bearer token',

'Content-Type': 'application/json'

}

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

4、发送带有查询参数的请求

可以通过URLSearchParams对象轻松地构建带有查询参数的URL。

const params = new URLSearchParams({ name: 'John Doe', age: 30 });

fetch(`https://api.example.com/data?${params}`)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));

三、异步与同步请求

1、使用async/await

为了简化Promise的链式调用,可以使用async/await语法。

async function fetchData() {

try {

const response = await fetch('https://api.example.com/data');

if (!response.ok) {

throw new Error('Network response was not ok ' + response.statusText);

}

const data = await response.json();

console.log(data);

} catch (error) {

console.error('There has been a problem with your fetch operation:', error);

}

}

fetchData();

2、同步请求(不推荐)

JavaScript中不推荐使用同步请求,因为它会阻塞主线程,影响用户体验。但如果确实需要,可以使用第三方库如XMLHttpRequest来实现。

四、在项目中使用fetch API

在实际项目中,fetch API可以用于多种场景,如用户认证、数据提交等。为了更好地管理项目中的网络请求,可以结合研发项目管理系统PingCode通用项目协作软件Worktile来进行项目管理和任务跟踪。

1、用户认证

在用户登录时,发送POST请求以提交用户凭据,并处理响应以获取身份验证令牌。

async function login(username, password) {

try {

const response = await fetch('https://api.example.com/auth/login', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({ username, password })

});

if (!response.ok) {

throw new Error('Login failed: ' + response.statusText);

}

const data = await response.json();

// 存储令牌

localStorage.setItem('token', data.token);

} catch (error) {

console.error('Login error:', error);

}

}

2、数据提交

在表单提交时,使用POST请求将数据发送到服务器,并处理响应以确认提交成功。

async function submitForm(formData) {

try {

const response = await fetch('https://api.example.com/forms/submit', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify(formData)

});

if (!response.ok) {

throw new Error('Form submission failed: ' + response.statusText);

}

const data = await response.json();

console.log('Form submitted successfully:', data);

} catch (error) {

console.error('Form submission error:', error);

}

}

3、文件上传

文件上传是一个常见需求,可以通过fetch API实现。

async function uploadFile(file) {

const formData = new FormData();

formData.append('file', file);

try {

const response = await fetch('https://api.example.com/upload', {

method: 'POST',

body: formData

});

if (!response.ok) {

throw new Error('File upload failed: ' + response.statusText);

}

const data = await response.json();

console.log('File uploaded successfully:', data);

} catch (error) {

console.error('File upload error:', error);

}

}

五、使用fetch API的最佳实践

1、封装fetch请求

为了提高代码的可维护性和重用性,可以将fetch请求封装成一个通用函数。

async function fetchData(url, options = {}) {

try {

const response = await fetch(url, options);

if (!response.ok) {

throw new Error('Network response was not ok ' + response.statusText);

}

return await response.json();

} catch (error) {

console.error('Fetch error:', error);

throw error;

}

}

// 使用封装的fetch函数

fetchData('https://api.example.com/data')

.then(data => console.log(data))

.catch(error => console.error(error));

2、处理超时

fetch API本身不支持请求超时,可以通过Promise.race来实现。

async function fetchWithTimeout(url, options = {}, timeout = 5000) {

const controller = new AbortController();

const { signal } = controller;

options.signal = signal;

const fetchPromise = fetch(url, options);

const timeoutPromise = new Promise((_, reject) =>

setTimeout(() => reject(new Error('Request timed out')), timeout)

);

try {

return await Promise.race([fetchPromise, timeoutPromise]);

} finally {

controller.abort();

}

}

// 使用带有超时的fetch函数

fetchWithTimeout('https://api.example.com/data')

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(error));

3、使用请求缓存

为了减少网络请求次数,可以使用浏览器的缓存功能。

async function fetchDataWithCache(url) {

const cacheKey = `cache_${url}`;

const cachedData = localStorage.getItem(cacheKey);

if (cachedData) {

return JSON.parse(cachedData);

}

const response = await fetchData(url);

localStorage.setItem(cacheKey, JSON.stringify(response));

return response;

}

// 使用缓存的fetch函数

fetchDataWithCache('https://api.example.com/data')

.then(data => console.log(data))

.catch(error => console.error(error));

六、总结

使用原生JavaScript的fetch API发送请求是处理网络请求的现代方法。通过fetch API,可以简洁地发送GET和POST请求,处理响应数据,并捕获错误。为了提高代码的可维护性和重用性,可以将fetch请求封装成通用函数,并结合研发项目管理系统PingCode通用项目协作软件Worktile来进行项目管理和任务跟踪。通过最佳实践,如封装请求、处理超时和使用缓存,可以进一步优化fetch API的使用。

相关问答FAQs:

1. 如何使用原生JS中的fetch函数发送GET请求?

  • 使用fetch函数可以发送GET请求,示例代码如下:
fetch('http://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // 处理响应数据
    console.log(data);
  })
  .catch(error => {
    // 处理错误
    console.log(error);
  });

2. 如何在原生JS中使用fetch函数发送POST请求并传递参数?

  • 使用fetch函数发送POST请求时,可以通过配置参数来传递数据,示例代码如下:
fetch('http://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username: 'john', password: 'secret' })
})
  .then(response => response.json())
  .then(data => {
    // 处理响应数据
    console.log(data);
  })
  .catch(error => {
    // 处理错误
    console.log(error);
  });

3. 如何在原生JS中使用fetch函数处理异步请求的错误?

  • 在使用fetch函数发送异步请求时,可以通过.catch()方法来捕获错误并进行处理,示例代码如下:
fetch('http://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // 处理响应数据
    console.log(data);
  })
  .catch(error => {
    // 处理错误
    console.log(error);
  });

在上述代码中,如果请求过程中出现错误,例如网络错误或服务器错误,会被.catch()方法捕获到,并执行相应的错误处理代码。

文章包含AI辅助创作,作者:Edit1,如若转载,请注明出处:https://docs.pingcode.com/baike/3924945

(0)
Edit1Edit1
免费注册
电话联系

4008001024

微信咨询
微信咨询
返回顶部