fetch网络请求封装
tby_37 人气:0export default ({ url, method = 'GET', data = null, }) => { // 请求配置 let options = { method } // data不为空时,它就是post请求 if (data) { options = { ...options, body: JSON.stringify(data), headers: { 'content-type': 'application/json' } } } return fetch(url, options) .then(res => res.json()) .then(data => data) }
使用
get
post
<script type="module"> import fetchApi from './js/fetch.js' const vm = new Vue({ el: '#app', data: { users: [] }, // 发起网络请求 mounted() { let url = 'http://localhost:3000/api/users' // fetchApi({ url }).then(data => console.log(data)) fetchApi({ url, method: 'POST', data: { id: 200, name: 'aaa' } }).then(data => console.log(data)) } }) </script>
加载全部内容