当前位置: 首页 > wzjs >正文

网站的站外推广手段微营销平台有哪些

网站的站外推广手段,微营销平台有哪些,企业销售型网站是什么,微信推广平台哪里找fetch() 是 JavaScript 用于发送 HTTP 请求的内置 API,功能强大,语法简洁。以下是 fetch 的语法规则及常见用法。 1. fetch 基本语法 fetch(url, options).then(response > response.json()) // 解析 JSON 响应体.then(data > console.log(data))…

fetch() 是 JavaScript 用于发送 HTTP 请求的内置 API,功能强大,语法简洁。以下是 fetch 的语法规则及常见用法。


1. fetch 基本语法

fetch(url, options).then(response => response.json()) // 解析 JSON 响应体.then(data => console.log(data))   // 处理数据.catch(error => console.error("Error:", error)); // 处理错误
  • url:请求的地址(必填)。
  • options:可选的请求配置对象(如 methodheadersbody 等)。

2. fetch 请求方法

(1)GET 请求

GET 请求用于获取数据,通常不需要 body

fetch("https://api.example.com/data").then(response => response.json()).then(data => console.log(data)).catch(error => console.error("Error:", error));

或带参数:

const params = new URLSearchParams({ id: 123, name: "Tom" });
fetch(`https://api.example.com/data?${params}`).then(response => response.json()).then(data => console.log(data));

(2)POST 请求

POST 用于发送数据,通常需要 bodyheaders

fetch("https://api.example.com/data", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ id: 123, name: "Tom" })
})
.then(response => response.json())
.then(data => console.log(data));

(3)PUT / PATCH 请求(更新数据)

  • PUT:完整更新资源
  • PATCH:部分更新资源
fetch("https://api.example.com/user/123", {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: "Updated Name" })
})
.then(response => response.json())
.then(data => console.log(data));

(4)DELETE 请求

DELETE 请求用于删除数据,通常不需要 body

fetch("https://api.example.com/user/123", {method: "DELETE"
})
.then(response => response.json())
.then(data => console.log(data));

3. fetch 选项(options)详解

fetch(url, {method: "POST", // 请求方法headers: { "Content-Type": "application/json" }, // 请求头body: JSON.stringify({ key: "value" }), // 请求体mode: "cors", // 跨域请求模式credentials: "include", // 携带 Cookiecache: "no-cache", // 缓存模式redirect: "follow" // 自动跟随重定向
})

常用 options 配置

配置项说明
method请求方法(GET、POST、PUT、DELETE、PATCH等)
headers请求头,例如 Content-TypeAuthorization
body发送的请求数据,通常为 JSON 或 FormData
modecors(跨域),same-origin(同源)
credentialsinclude(携带 Cookie),omit(不带 Cookie)
cacheno-cache(不缓存),reload(强制刷新)
redirectfollow(自动重定向),error(遇到重定向报错)

4. 处理响应(Response 对象)

fetch 返回的是一个 Promise,解析后得到 Response 对象:

fetch("https://api.example.com/data").then(response => {console.log(response.status);  // HTTP 状态码console.log(response.headers); // 响应头return response.json();        // 解析 JSON}).then(data => console.log(data));

Response 方法

方法作用
response.text()解析为文本格式
response.json()解析为 JSON
response.blob()解析为 Blob(二进制数据,如图片)
response.arrayBuffer()解析为 ArrayBuffer
response.formData()解析为 FormData

5. 处理错误

fetch 只有在网络错误时才会进入 catch,如果服务器返回 4xx 或 5xx 需要手动抛出异常:

fetch("https://api.example.com/data").then(response => {if (!response.ok) {throw new Error(`HTTP error! Status: ${response.status}`);}return response.json();}).then(data => console.log(data)).catch(error => console.error("Fetch error:", error));

6. async/await 方式

fetch 也可以和 async/await 搭配使用,使代码更清晰:

async function fetchData() {try {const response = await fetch("https://api.example.com/data");if (!response.ok) {throw new Error(`HTTP error! Status: ${response.status}`);}const data = await response.json();console.log(data);} catch (error) {console.error("Fetch error:", error);}
}fetchData();

7. 进阶用法

(1)携带 Cookie(跨域请求)

如果请求涉及跨域并需要携带 Cookie,必须设置 credentials

fetch("https://api.example.com/data", {method: "GET",credentials: "include" // 允许携带 Cookie
});

(2)上传文件

使用 FormData 进行文件上传:

const formData = new FormData();
formData.append("file", fileInput.files[0]);fetch("https://api.example.com/upload", {method: "POST",body: formData
})
.then(response => response.json())
.then(data => console.log(data));

(3)超时处理

fetch 本身不支持超时,需要用 Promise.race() 处理:

function fetchWithTimeout(url, timeout = 5000) {return Promise.race([fetch(url),new Promise((_, reject) =>setTimeout(() => reject(new Error("Request Timeout")), timeout))]);
}fetchWithTimeout("https://api.example.com/data").then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error));

8. 总结

用法代码示例
基本 GETfetch(url).then(res => res.json()).then(console.log);
POST 发送 JSONfetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) })
处理错误fetch(url).then(res => { if (!res.ok) throw new Error(res.status); return res.json(); })
携带 Cookiefetch(url, { credentials: "include" })
上传文件fetch(url, { method: "POST", body: formData })
超时处理Promise.race([fetch(url), new Promise((_, r) => setTimeout(() => r(new Error("Timeout")), 5000))])
http://www.dtcms.com/wzjs/823782.html

相关文章:

  • 营口建设工程信息网站往国外卖货的平台
  • 请打开123720的网站百度本地手机网站建设
  • 自己做网站需要买哪些自己给自己网站做seo
  • 导航滑动整屏网站浙江公司响应式网站建设推荐
  • wordpress拖动建站海南百度网站建设
  • 交互设计包含网站设计售后软件网站开发
  • 江门网站免费制作网站集约化建设规划
  • 大连手机网站设计wordpress有哪些网站
  • 网站制作完成后网站的页面由什么组成
  • 访问网站的原理百度网站好评
  • 开发网站需要什么技术2022vps 做网站
  • 网站建设的主要技术指什么软件分类信息网站平台有哪些
  • 网页制作成品模板网站网站宣传虚假处罚标准
  • 网站进度条网站的实施方案
  • 公司在网站做广告怎么做分录网站显示乱码怎么办啊
  • 网站开发的经济效益分析淘客网站开发教程
  • 注册网站域名网站建设开发电销话术
  • 简述做个人网页的思路怎么看网站做没做seo
  • 摄影网站规划设计书教育机构网站建设
  • 百度公司做网站优化多少钱东莞前10大互联网公司
  • 南京制作网站培训学校wordpress数据库进不去
  • 网站建设公司 上大黔门官方网站建设
  • 无锡市网站设计被墙网站查询
  • 可以做动漫网站的源码源码惠州惠城网站建设
  • 网站建设项目经验怎么写做网站公司关键词
  • 重庆网站推广报价深圳市宝安区中心医院
  • 小说网站建设费用山西省消防总队建设工程备案网站
  • 湖南省网站设计公司大良做网站的公司
  • 成都私人做网站建设免费拓客软件排行榜
  • 徐州cms建站系统怎么做彩票网站