广州网站平台怎么做,2024北京又开始核酸了吗今天,广东专业移动网站建设哪家好,网站页面设计技术参数fetch 是一个现代、强大的、基于 Promise 的网络请求 API#xff0c;用于在浏览器中发起网络请求#xff08;如异步获取资源#xff09;。它提供了一种更加简洁和灵活的方式来替代 XMLHttpRequest。下面是 fetch 的基本使用方法和一些示例。
基本语法
fetch(url, options)…fetch 是一个现代、强大的、基于 Promise 的网络请求 API用于在浏览器中发起网络请求如异步获取资源。它提供了一种更加简洁和灵活的方式来替代 XMLHttpRequest。下面是 fetch 的基本使用方法和一些示例。
基本语法
fetch(url, options).then(response {// 处理响应if (!response.ok) {throw new Error(Network response was not ok);}return response.json(); // 或者 response.text(), response.blob() 等取决于你需要的数据类型}).then(data {// 处理响应数据console.log(data);}).catch(error {// 处理错误console.error(There was a problem with your fetch operation:, error);});参数
url要请求的资源的 URL。options可选一个配置项对象用于自定义请求比如设置请求方法GET、POST 等、请求头Headers、请求体Body等。
示例
GET 请求
fetch(https://api.example.com/data).then(response {if (!response.ok) {throw new Error(Network response was not ok);}return response.json();}).then(data {console.log(data);}).catch(error {console.error(Fetch error:, error);});POST 请求
const url https://api.example.com/items;
const data { name: New Item, description: This is a new item. };fetch(url, {method: POST, // 或者 PUTheaders: {Content-Type: application/json,},body: JSON.stringify(data),
})
.then(response response.json())
.then(data console.log(data))
.catch((error) console.error(Error:, error));注意事项
fetch 不会自动处理 JSON 转换因此如果你期望获取 JSON 格式的数据你需要在 .then() 中调用 response.json()。fetch 只会拒绝reject网络错误而不会对 HTTP 错误状态码如 404 或 500进行拒绝。因此你需要检查 response.ok等同于 response.status 200 response.status 300来确保请求成功。fetch 遵循 CORS跨源资源共享策略因此如果你从前端应用向不同源的服务器发送请求需要确保服务器支持 CORS。默认情况下fetch 不会发送或接收任何 cookies也不会添加任何认证信息到请求中。如果你需要发送 cookies需要将 credentials 选项设置为 include。
fetch(url, {credentials: include,
})
.then(response response.json())
.then(data console.log(data))
.catch(error console.error(Error:, error));