您现在的位置是:网站首页> 编程资料编程资料
fetch跨域问题的使用详解_javascript技巧_
2023-05-24
301人已围观
简介 fetch跨域问题的使用详解_javascript技巧_
一、介绍
fetch 提供了一个获取资源的接口 (包括跨域)。
fetch 的核心主要包括:Request , Response , Header , Body
利用了请求的异步特性 --- 它是基于 promise 的
1.作用:fetch这个API, 是专门用来发起Ajax请求的;
fetch('/url').then(data=>{ return data.text(); }).then(ret=>{ //注意,这里才是得到的最终数据 console.log(ret); });2.fetch是由原生JS提供的API,专门用来取代XHR这个对象的;
fetch("请求的url地址") .then(response => res.json() ) .then(data => console.log(data)) //注意: 第一个.then 中获取到的不是最终数据,而是一个中间的数据流对象; // 注意: 第一个 .then 中获取到的数据, 是一个 Response 类型对象; // 注意: 第二个 .then 中,获取到的才是真正的 数据;3.发起Get 请求
// 默认 fetch("url") 的话, 发起的是 Get 请求 fetch("url") .then(response => { //这个 response 就是 服务器返回的可读数据流, 内部存储的是二进制数据 // .json() 的作用,就是 读取 response 这个二进制数据流,并把 读取到的数 // 据,转为 JSON 格式的Promise 对象 return response.json() }) .then(data => { //这离 第二个 .then 中拿到的 data, 就是最终的数据 console.log(data) })4.发起Post请求
var sendDate = new URLSearchParams() sendDate.append("name",'ls') sendDate.append("age", 30) fetch("url", { method: "post", body: sendDate //要发给服务器的数据 }) .then(response => response.json()) .then(data => console.log(data))fetch(URL, { method: 'post', body:JSON.stringify(obj), headers:{ 'Content-Type': 'application/json' } }) .then(function (response) { return response.text(); }) .then(function (myJson) { alert(myJson); });到此这篇关于fetch跨域问题的使用详解的文章就介绍到这了,更多相关fetch跨域问题内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- JS样式获取的封装方法实例详解_javascript技巧_
- 前端Vue.js实现json数据导出到doc_vue.js_
- react-native 实现渐变色背景过程_React_
- Node.js 源码阅读深入理解cjs模块系统_node.js_
- 微信小程序Vant组件库的安装与使用教程_javascript技巧_
- React 全面解析excel文件_React_
- 详解vite如何支持cjs方案示例_vue.js_
- React中Suspense及lazy()懒加载及代码分割原理和使用方式_React_
- vue元素样式实现动态改变方法介绍_vue.js_
- Electron store及shareObject进程间数据交互存储功能封装_vue.js_
