当前位置: 移动技术网 > IT编程>开发语言>JavaScript > fetch和axios

fetch和axios

2020年07月17日  | 移动技术网IT编程  | 我要评论

一,fetch

XMLHttpRequest 是一个设计粗糙的 API,配置和调用方式非常混乱, 而且基于事件的异步模型写起来不友好,容易回调地狱。

fetch缺点是

兼容性不好 https://github.com/camsong/fetch-ie8
Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: ‘include’})

get

fetch("url").then(res=>res.json()).then(res=>{console.log(res)})
fetch("url").then(res=>res.text()).then(res=>{console.log(res)})


post

fetch("url",{ 
 method:'post', 
 headers: { 
  "Content‐Type": "application/x‐www‐form‐urlencoded" 
   },
body: "name=kerwin&age=100"
}).then(res=>res.json()).then(res=>{console.log(res)});
fetch("/users",{
method:'post',
headers: {
"Content‐Type": "application/json"
},
 body: JSON.stringify({
 name:"shirley",
 age:100
 })
 }).then(res=>res.json()).then(res=>{console.log(res)});

例子:

<div id="box">
    <button @click="handleFetch">fetch</button>
    <ul>
        <li v-for="item in itemList" :key="item.id">
            {{ item.nm}}
            <img :src="handleImg(item.img)">
        </li>
    </ul>
</div>
new Vue({
     el : '#box',
     data :{
         itemList : []
     },
     methods: {
         handleFetch(){
             fetch('./json/maoyan.json')
             .then(res=>res.json())
             .then(res=>{
                 // console.log(res)
                 this.itemList = res.coming
             })
         },
         handleImg(path){
             return path.replace('w.h','')+"@1l_1e_1c_128w_180h"
         }
     }
 })

二,axios

基于promise封装

methods: {
	handleClick(){
		axios.get('./json/maoyan.json').then(res=>{
			console.log(res)
		}).catch(err=>{
			console.log(err)
		})
	}
}

get

methods: {
	handleClick(){
		axios.get('./json/maoyan.json',{
			params:{
				name: 'shirley',
				age : 20
			}
		}).then(res=>{
			console.log(res)
		}).catch(err=>{
			console.log(err)
		})
	}
}

post
post不需要写params

methods: {
	handleClick(){
		axios.post('/api/login',{
			username:'shirley',
			password: '123'
		}).then(res=>{
			console.log(res.data)
		}).catch(err=>{
			console.log(err)
		})
	}
}

跨域的三种方式

1.需要靠后端设置字段 , cors跨域解决方案
网站中 Response Headers 中 有 Access-Control- Allow-Origin : * 代表允许跨域

2.如果后端不设置 ,需要靠前端来反向代理

3.jsonp接口 ,前后端协作 ,axios不支持jsonp

axios请求数据 ,传请求头Headers
卖座前后端的数据通过字段 X-Client-Info 和X-Host

以前jquery的时候,可以直接传header , 只要把请求字段带来就可以。

 $.ajax({headers:{},data:{},type:''})
 handleClick(){
	axios({
		url:'https://.......',
		methods : 'get/post'
		headers :{
			'X-Client-Info' :'{"a":"3000","ch":"1002"}', //传过来的是对象不行,要改成字符串
			'X-Host' : 'mall.film-ticket.film.list'
		}
	}).then(res=>{
		console.log(res.data)
	})
}

jquery支持jsonp
axios不支持jsonp

本文地址:https://blog.csdn.net/Shirley_0513/article/details/107364466

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网