数据请求
框架后基本不会再用原生的ajax
ajax不符合模块化思想
前端如何模拟数据
- mock.js
- 安装:npm i mockjs -S
- 使用:去官网找需要的模板
- easymock
- 用法去npmjs查,用法相似
- jsonserver
- 同上
- 前端模拟数据要根据后端给的接口来做模拟数据,根据返回值来做
两个新的数据请求方案
-
第三方模块:axios
- 支持npm、CDN
安装:npm install axios -S
- 基于promise的http请求
- 特征:
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
- axios的返回值是一个封装对象,data属性是返回结果
- 设置请求地址的baseURL:
//示例 axios.defaults.baseURL='http://localhost:3000';
- get 请求
//get请求 axios({ url:'', method:'get', params:{ //传给后端的参数 } }).then(res=>console.log(res)) .catch(err=>console.log(err)) //法二 axios.get({ url:'', params:{ //传给后端的参数 } }).then(res=>console.log(res)) .catch(err=>console.log(err))
- post请求
//post请求 json提交 axios({ url:'', method:'post', data:{ //传递的数据 } }).then(res=>console.log(res)) .catch(err=>console.log(err)) //post请求 formdata (querystring)表单提交 //示例:传usernam和password给后端 axios({ const p =new URLSearchParams() const {username,password}=this p.append('username',username) p.append('password',password)//得到数据参数携带对象 url:'', method:'post', data:p }).then(res=>console.log(res)) .catch(err=>console.log(err)) //还可以使用axios.post()方法 传参数和属性同上
- put请求
//put请求 //put请求底层是get请求 axios({ url:'', method:'put', params:{ //传给后端的参数 } }).then(res=>console.log(res)) .catch(err=>console.log(err))
- delete请求
//delete请求 //delete请求底层也是get请求 axios({ url:'', method:'delete', params:{ //传给后端的参数 } }).then(res=>console.log(res)) .catch(err=>console.log(err))
-
原生js提供:fetch
-
由原生js提供 ajax的封装版本
-
复合模块化思想
-
用的也是promise
-
在浏览器呈现fetch字样
-
返回的数据没有经过包装处理
-
get请求
//传的数据要跟在url后面 fetch('url?data',{ method:'get' }) .then(data=>data.json()) .then(res=>console.log(res)) .catch(err=>console.log(err))
- post请求
//表单提交发送 fetch('url',{ method:'post', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交 }), body: new URLSearchParams([["username", 'zhangsan'],["password", 123]]).toString() // 这里是请求对象 }) .then(data=>data.json()) .then(res=>console.log(res)) .catch(err=>console.log(err)) //json数据提交 fetch(`${ baseURL }/users`, { method: 'POST', // or 'PUT' body: JSON.stringify({ username: 'zhangsan', password: 123 }), headers: new Headers({ 'Content-Type': 'application/json' }) }) .then(data=>data.json()) .then(res=>console.log(res)) .catch(err=>console.log(err))
-