一、ajax、umi-request 、axios 和 fetch 的区别
1.ajax:
1、本身是针对MVC的编程
2、单纯使用ajax却要引入整个JQuery非常的不合理
3、配置和调用方式非常混乱
2.axios:
1、从浏览器中创建 XMLHttpRequest
2、支持 Promise API
3、从 node.js 创建 http 请求
4、拦截请求和响应
5、转换请求和响应数据
6、自动转换JSON数据
3.fetch:
1、fetch是原生js,没用使用 XMLHttpRequest对象
2、使用了ES6中的promise对象,基于标准 Promise 实现,支持 async/await
3、更关注分离,拥有更好的语义化;
4、缺点
*仅当网络故障时或请求被阻止时,才会标记为 reject;
*不会主动发送cookie,需要手动设置;
4.umi-request:
{
// 'method' 是创建请求时使用的方法
method: 'get', // default
// 'params' 是即将于请求一起发送的 URL 参数,参数会自动 encode 后添加到 URL 中
// 类型需为 Object 对象或者 URLSearchParams 对象
params: { id: 1 },
// 'paramsSerializer' 开发者可通过该函数对 params 做序列化(注意:此时传入的 params 为合并了 extends 中 params 参数的对象,如果传入的是 URLSearchParams 对象会转化为 Object 对象
paramsSerializer: function (params) {
return Qs.stringify(params, { arrayFormat: 'brackets' })
},
// 'data' 作为请求主体被发送的数据
// 适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: { name: 'Mike' },
// 'headers' 请求头
headers: { 'Content-Type': 'multipart/form-data' },
// 'timeout' 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求超过了 'timeout' 时间,请求将被中断并抛出请求异常
timeout: 1000,
// ’prefix‘ 前缀,统一设置 url 前缀
// ( e.g. request('/user/save', { prefix: '/api/v1' }) => request('/api/v1/user/save') )
prefix: '',
// ’suffix‘ 后缀,统一设置 url 后缀
// ( e.g. request('/api/v1/user/save', { suffix: '.json'}) => request('/api/v1/user/save.json') )
suffix: '',
// 'credentials' 发送带凭据的请求
// 为了让浏览器发送包含凭据的请求(即使是跨域源),需要设置 credentials: 'include'
// 如果只想在请求URL与调用脚本位于同一起源处时发送凭据,请添加credentials: 'same-origin'
// 要改为确保浏览器不在请求中包含凭据,请使用credentials: 'omit'
credentials: 'same-origin', // default
// ’useCache‘ 是否使用缓存,当值为 true 时,GET 请求在 ttl 毫秒内将被缓存,缓存策略唯一 key 为 url + params + method 组合
useCache: false, // default
// ’ttl‘ 缓存时长(毫秒), 0 为不过期
ttl: 60000,
// 'maxCache' 最大缓存数, 0 为无限制
maxCache: 0,
// 根据协议规范, GET 请求用于获取、查询服务端数据,在数据更新频率不频繁的情况下做必要的缓存能减少服务端的压力,因为缓存策略是默认对 GET 请求做缓存,但对于一些特殊场景需要缓存其他类型请求的响应数据时,我们提供 validateCache 供用户自定义何时需要进行缓存, key 依旧为 url + params + method
validateCache: (url, options) => { return options.method.toLowerCase() === 'get' },
// 'requestType' 当 data 为对象或者数组时, umi-request 会根据 requestType 动态添加 headers 和设置 body(可传入 headers 覆盖 Accept 和 Content-Type 头部属性):
// 1. requestType === 'json' 时, (默认为 json )
// options.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/json;charset=UTF-8',
// ...options.headers,
// }
// options.body = JSON.stringify(data)
// 2. requestType === 'form' 时,
// options.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
// ...options.headers,
// };
// options.body = query-string.stringify(data);
// 3. 其他 requestType
// options.headers = {
// Accept: 'application/json',
// ...options.headers,
// };
// options.body = data;
requestType: 'json', // default
// ’parseResponse‘ 是否对请求返回的 Response 对象做格式、状态码解析
parseResponse: true, // default
// ’charset‘ 当服务端返回的数据编码类型为 gbk 时可使用该参数,umi-request 会按 gbk 编码做解析,避免得到乱码, 默认为 utf8
// 当 parseResponse 值为 false 时该参数无效
charset: 'gbk',
// 'responseType': 如何解析返回的数据,当 parseResponse 值为 false 时该参数无效
// 默认为 'json', 对返回结果进行 Response.text().then( d => JSON.parse(d) ) 解析
// 其他(text, blob, arrayBuffer, formData), 做 Response[responseType]() 解析
responseType: 'json', // default
// 'throwErrIfParseFail': 当 responseType 为 json 但 JSON.parse(data) fail 时,是否抛出异常。默认不抛出异常而返回 Response.text() 后的结果,如需要抛出异常,可设置 throwErrIfParseFail 为 true
throwErrIfParseFail: false, // default
// 'getResponse': 是否获取源 Response, 返回结果将包含一层: { data, response }
getResponse: false,// default
// 'errorHandler' 统一的异常处理,供开发者对请求发生的异常做统一处理,详细使用请参考下方的错误处理文档
errorHandler: function(error) { /* 异常处理 */ },
// 'cancelToken' 取消请求的 Token,详细使用请参考下方取消请求文档
cancelToken: null,
}
umi-request——官方的方法:
import request from 'umi-request';
request('/api/v1/xxx', {
method: 'get',
params: { id: 1 }
})
.then( response => { console.log(response);})
.catch( error => { console.log(error); });
request('/api/v1/user', {
method: 'post',
data: { name: 'Mike'}
})
.then(function (response) { console.log(response); })
.catch(function (error) { console.log(error); });
umi-request——antd中的用法:
import { extend } from 'umi-request';
const request = extend({
prefix: '/api/v1',
timeout: 1000,
headers: {
'Content-Type': 'multipart/form-data',
'X-Token':'Token'
}
});
request.get('/user')
.then(function (response) { console.log(response); })
.catch(function (error) { console.log(error); });
二、跨域
- fetch的跨域方法是在请求头添加
fetch(url,{
method:'post',
mode:"cors", //允许跨域 no-cors不允许跨域
// credentials:"include", //跨域请求时是不带cookie的,添加该属性表示强制加入凭据头,请求时就会携带cookie。但是如果加上这个属性,那么服务器的Access-Control-Allow-Origin 就不能是‘*’,否则会报下面的错误。
headers:new Headers({
'Content-Type': 'application/x-www-form-urlencoded', // 指定提交方式为表单提交
}),
body:formdate
})
.then( response => response.json())
.then( json => { console.log(json) }
.catch( error => { console.log('error',error)})
- react 方法:针对react版本^16.6.0有多种解决方案
https://www.cnblogs.com/theblogs/p/10394496.html
https://www.jianshu.com/p/070faf348a6a
在packge.json加入加上proxy代理配置
"proxy": "http://0.0.2.89:7300"
- 谷歌浏览器跨域
在 chrome 浏览器右击属性 ---> 快捷方式 ----> 目标,在问价名后面加入 --disable-web-security --user-data-dir
打开浏览器,显示稳定性和安全性有所下降,就成功跨域了。
- 使用 Nginx 跳转,
三、MVC 和 MVVM 的区别:
【模型】指的是后端传递的数据。
【视图】指的是所看到的页面。
【视图模型】mvvm模式的核心,它是连接view和model的桥梁。
MVC是单向通信。也就是View跟Model,必须通过Controller来承上启下。