vue 1.x 的版本提供了一个封装库 vue-resource , 可是到了vue 2.x版本以后,这个就弃用了
vue-resource使用方法和 axios 类似度在 95%
vue-resouce有jsonp方法,可是axios是没有的javascript
vue2.x版本咱们最用使用的数据请求是 axios 和 fetchphp
axios获得的结果会进行一层封装,而fetch会直接获得结果html
举例:
axios前端
{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data: 3 headers: {content-type: "text/html; charset=UTF-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" __proto__: Object
fetchvue
3
// 统一设置请求头 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; let params = new URLSearchParams() // params.append(key,value) params.append('a',1) params.append('b',2) axios({ url: 'http://localhost/post.php', method: 'post', data: params, headers: { //单个请求设置请求头 'Content-Type': "application/x-www-form-urlencoded" } }) .then(res => { console.log( res ) }) . catch( error => { if( error ){ throw error } })
fetch('http://localhost/get.php?a=1&b=2') .then(res=> res.text()) // 数据格式化 res.json() res.blob() .then(data =>console.log( data ) .catch(error => { if( error ){ throw error } }) // 注意事项: // A: fetch 的 get 请求的参数是直接链接在url上的, 咱们能够使用Node.js提供的url或是qureystring模块来将 // Object --> String //B: fetch 的请求返回的是Promise对象,因此咱们能够使用.then().catch(),可是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是能够拿到格式化后的数据 // 格式化处理方式有 fetch('./data.json') .then(res=>res.json()) //res.text() res.blob() .then( data => console.log(data)) .catch( error => console.log( error ))
post() { fetch('http://localhost/erjieduan/post.php', { method: 'post', headers: new Headers({ //解决跨域 'Content-Type': "application/x-www-form-urlencoded" }), body: new URLSearchParams([ ['a', 2], ['b', 1] ]).toString() }) .then(res => res.text()) .then(data => console.log(data)) .catch(error => { if (error) throw error }) },