get post head put delete option …
axios得到的结果会进行一层封装,而fetch会直接得到结果
举例: 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__: Object1.get方法
A: 无参数 axios.get(url) .then(res=>console.log(res) .catch(error=>conosle.log(error)) B: 有参数 axios({ url: 'http://xxx', method: 'get' //默认就是get,这个可以省略, params: { key: value } })2.post
注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑解决步骤: 先设置请求头实例化 URLSearchParams的构造器函数得到params对象使用params对象身上的append方法进行数据的传参 // 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 } })1.get
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 } })注意事项:
1. fetch 的 get 请求的参数是直接连接在url上的 我们可以使用Node.js提供的url或是qureystring模块来将 Object --> String 2. 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 ))2.post
post () { fetch( 'http://localhost/post.php',{ method: 'POST', headers: new Headers({ //解决跨域 'Content-Type': "application/x-www-form-urlencoded" }), body: new URLSearchParams([ // 进行参数的修改 ["a",1], ["b",2] ]).toString() }) .then( res => res.text() ) // res.json() res.blob() 不常用 .then( data => console.log( data )) .catch( error => { if( error ) throw error }) },