
- export 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>
以上就是fetch网络请求封装示例详解的详细内容,更多关于fetch网络请求封装的资料请关注w3xue其它相关文章!