Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

axios 调用 jeecg-boot 传入 token 的方法 #31

Open
topcss opened this issue Jul 11, 2019 · 0 comments
Open

axios 调用 jeecg-boot 传入 token 的方法 #31

topcss opened this issue Jul 11, 2019 · 0 comments
Labels

Comments

@topcss
Copy link
Owner

topcss commented Jul 11, 2019

jeecg-boot 本身已经实现了 ajax 的调用,参照它改写一份简化版即可。最核心的就是 request interceptor 方法,调用的时候自动加入。

import axios from 'axios'
import domain from '../conf'
import storage from './storage'

// 创建 axios 实例
const service = axios.create({
  baseURL: domain.baseUrl,
  timeout: 6000 // 请求超时时间
})

// request interceptor
service.interceptors.request.use(config => {
  const token = storage.localGet('tokenId')
  if (token) {
    config.headers['X-Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

export const fetch = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'get',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      params: params
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export const post = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url: url,
      data: data
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
@topcss topcss added the ☕Java label Jul 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant