第一部分:cookie插件使用
一、安装
npm install js-cookie --save
二、引用
import Cookies from 'js-cookie'
三、一般使用
1.存到Cookie去
// Create a cookie, valid across the entire site:Cookies.set('name', 'value');// Create a cookie that expires 7 days from now, valid across the entire site:Cookies.set('name', 'value', { expires: 7 });// Create an expiring cookie, valid to the path of the current page:Cookies.set('name', 'value', { expires: 7, path: '' });
2.在Cookie中取出
// Read cookie:Cookies.get('name'); // => 'value'Cookies.get('nothing'); // => undefined// Read all visible cookies:Cookies.get(); // => { name: 'value' }
3.删除
// Delete cookie:Cookies.remove('name');// Delete a cookie valid to the path of the current page:Cookies.set('name', 'value', { path: '' });Cookies.remove('name'); // fail!Cookies.remove('name', { path: '' }); // removed!
四、特殊使用(在Cookie中存对象)
跟一般使用不同的是,从Cookie中取出的时候,要从字符串转换成json格式:
const user = {name: 'lia',age: 18}Cookies.set('user', user)const liaUser = JSON.parse(Cookies.get('user'))
第二部分:ajax和axios区别
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios({undefinedurl: 'http://jsonplaceholder.typicode.com/users',method: 'get',responseType: 'json', // 默认的data: {undefined//'a': 1,//'b': 2,}}).then(function (response) {undefinedconsole.log(response);console.log(response.data);}).catch(function (error) {undefinedconsole.log(error);})
AJAX 是与服务器交换数据并更新部分网页的,在不重新加载整个页面的情况下。
Ajax = 异步 JavaScript 和 XML(标准通用标记语言的子集)。
$.ajax({undefinedurl: 'http://jsonplaceholder.typicode.com/users',type: 'get',dataType: 'json',data: {undefined//'a': 1,//'b': 2,},success: function (response) {undefinedconsole.log(response);}})
第三部分:axios请求携带cookie配置
import axios from 'axios';get = (url, params) => {return axios({method: 'get',withCredentials: true, // 允许请求后端接口的时候携带cookieurl,params,data: undefined,});};const post = (url, data) => {return axios({method: 'post',withCredentials: true,url,pararms: undefined,data,});};export default { get, post };
第四部分:ajax请求
XMLHttpRequest是一个浏览器接口,使得Javascript可以进行HTTP(S)通信。
我们在浏览器中使用XMLHTTPRequest对象在服务器之间通信,传输的数据是使用XML的方式,但最终还是会被转换成json数据格式来被我们使用。
var xhr = new XMLHttpRequest(); // 新建一个XMLHttpRequest实例xhr.open('GET', url);xhr.responseType = 'json';xhr.withCredentials = true; // 允许携带cookiexhr.send(); // 向远程主机发出一个HTTP请求xhr.timeout = 3000; // 设置超时时间// 需要监控XMLHttpRequest对象的状态变化,指定回调函数xhr.onreadystatechange = function(){if ( xhr.readyState == 4 && xhr.status == 200 ) {alert( xhr.responseText );} else {alert( xhr.statusText );}};
