Fetch get请求,post请求快速入门,新人手册

曹え 5811 发布于:2024-01-05 07:39:20

详细教程:https://zhuanlan.zhihu.com/p/644596660


快速使用方法:


封装js

import 'ant-design-vue/dist/reset.css';
import { message } from 'ant-design-vue';
const [messageApi, contextHolder] = message.useMessage();

function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

async function commonFetcdh(url, options, method = 'GET') {
	  const searchStr = obj2String(options)
	  let initObj = {}
	  if (method === 'GET') { // 如果是GET请求,拼接url
		url += '?' + searchStr
		initObj = {
			method: method,
			credentials: 'same-origin'
		}
	} else {
	  initObj = {
		method: method,
		credentials: 'same-origin',
		headers: new Headers({
		  'Accept': 'application/json',
		  'Content-Type': 'application/x-www-form-urlencoded'
		}),
		body: searchStr
	  }
	}
	messageApi.info('Hello, Ant Design Vue!');
	let res = await fetch(url, initObj)
	let json = await res.json()
	return json
}



const G = {
	test(){
		return G.apiurl()
	},
	apiurl(){
		return 'https://xxx.cn'
	},
	GET(url, options) {
	  return commonFetcdh(G.apiurl() + url, options, 'GET')
	},
	POST(url, options) {
	  return commonFetcdh(G.apiurl() + url, options, 'POST')
	}
}

export default G


使用方法:

<script setup>
import { getCurrentInstance, reactive } from 'vue';
const { proxy } = getCurrentInstance()

// 提交表单后调用登录接口
const onFinish = values => {
  proxy.G.POST('/logina/index',formState).then( res =>{
	  console.log(res)
  })
};

</script>


觉得有用请点个赞吧!
1 145