在一個項目中,數據的請求發送數據是最為重要的,不可能我們的數據都是自己進行編寫的
在react中官方推薦使用的方法是fetch。當然它里面也可以使用vue中的axios請求數據,jQuery的$.ajax 以及元素ajax
下面重點說一下fetch
get方法非常簡單,
1 componentDidMount() { 2 fetch('http://127.0.0.1:8100/getAaa') 3 .then(res=>res.json()) 4 .then(json=>this.setState({list: json})) 5 }
post方法相對於get有點復雜,
1 add() { 2 fetch('http://127.0.0.1:8100/getDel',{ 3 method:'post',//改成post 4 mode: 'cors',//跨域 5 headers: {//請求頭 6 'Content-Type': 'application/x-www-form-urlencoded' 7 }, 8 body:"..."//向服務器發送的數據 9 }) 10 .then(res=>res.json()) 11 .then(json=>{console.log(json)}) 12 }
以上就是關於react fetch兩種使用方法
有什么不足的或者不對的歡迎大家指出