自定义封装ajax请求

时间:2024-10-02 20:01:39
  • let axios = (function () {
  • let BaseUrl = 'http://localhost:8888/api'
  • function ajax_get({ url, query }) {
  • return new Promise((resolve, reject) => {
  • if (!url) {
  • return alert('你没有传递url')
  • }
  • let str = ''
  • if (query) {
  • str = '?'
  • for (let key in query) {
  • str += `${key}=${query[key]}&`
  • }
  • str = str.slice(0, -1)
  • }
  • let xhr = new XMLHttpRequest()
  • xhr.open('get', query ? BaseUrl+url + str : BaseUrl+url)
  • // 设置请求头 携带token
  • xhr.setRequestHeader('authorization',cookie.getItem('token') || null)
  • xhr.send()
  • xhr.onreadystatechange = () => {
  • if (xhr.readyState == 4) {
  • if (xhr.status == 200) {
  • resolve(JSON.parse(xhr.response))
  • } else {
  • reject(JSON.parse(xhr.response))
  • }
  • }
  • }
  • })
  • }
  • function ajax_post({ url, query }) {
  • return new Promise((resolve, reject) => {
  • if (!url) {
  • return alert('你没有传递地址')
  • }
  • let xhr = new XMLHttpRequest()
  • xhr.open('post', BaseUrl+url)
  • xhr.setRequestHeader('authorization',cookie.getItem('token') || null)
  • xhr.setRequestHeader('content-type', 'application/json')
  • xhr.send(query ? JSON.stringify(query) : null)
  • xhr.onreadystatechange = () => {
  • if (xhr.readyState == 4) {
  • if (xhr.status == 200) {
  • resolve(JSON.parse(xhr.response))
  • } else {
  • reject(JSON.parse(xhr.response))
  • }
  • }
  • }
  • })
  • }
  • function ajax_put({ url, query }) {
  • return new Promise((resolve, reject) => {
  • if (!url) {
  • return alert('你没有传递地址')
  • }
  • let xhr = new XMLHttpRequest()
  • xhr.open('put', BaseUrl+url)
  • xhr.setRequestHeader('authorization',cookie.getItem('token') || null)
  • xhr.setRequestHeader('content-type', 'application/json')
  • xhr.send(query ? JSON.stringify(query) : null)
  • xhr.onreadystatechange = () => {
  • if (xhr.readyState == 4) {
  • if (xhr.status == 200) {
  • resolve(JSON.parse(xhr.response))
  • } else {
  • reject(JSON.parse(xhr.response))
  • }
  • }
  • }
  • })
  • }
  • function ajax_upload({ url, query }) {
  • return new Promise((resolve, reject) => {
  • if (!url) {
  • return alert('你没有传递地址')
  • }
  • let xhr = new XMLHttpRequest()
  • xhr.open('post', BaseUrl+url)
  • xhr.setRequestHeader('authorization',cookie.getItem('token') || null)
  • // ('content-type', 'application/json')
  • xhr.send(query)
  • xhr.onreadystatechange = () => {
  • if (xhr.readyState == 4) {
  • if (xhr.status == 200) {
  • resolve(JSON.parse(xhr.response))
  • } else {
  • reject(JSON.parse(xhr.response))
  • }
  • }
  • }
  • })
  • }
  • let options = {
  • get: ajax_get,
  • post: ajax_post,
  • put:ajax_put,
  • upload:ajax_upload
  • }
  • return options
  • })()