方式一: 各API封装为单独的函数

在package.json中为baseUrl添加proxy (React适用)

  1. "proxy": "https://www.xxxx.com/",

封装API

  1. import axios from 'axios'
  2. const baseUrl = '/api/notes'
  3. let token = null
  4. const setToken = newToken => {
  5. token = `bearer ${newToken}`
  6. }
  7. const getAll = async () => {
  8. const response = await axios.get(baseUrl)
  9. return response.data
  10. }
  11. const create = async newObject => {
  12. const config = {
  13. headers: { Authorization: token },
  14. }
  15. const response = await axios.post(baseUrl, newObject, config)
  16. return response.data
  17. }
  18. const update = async (id, newObject) => {
  19. const response = await axios.put(`${ baseUrl } /${id}`, newObject)
  20. return response.data
  21. }
  22. export default { getAll, create, update, setToken }

方法二: 封装为一个全能函数

  1. import axios from 'axios'
  2. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
  3. axios.defaults.baseURL = 'http://xxx.com'
  4. axios.defaults.withCredentials = true // 跨域
  5. export default function request(url: string, type='GET', data={}){
  6. return new Promise((resolve, reject) => {
  7. const option:any = {
  8. url,
  9. method: type,
  10. validateStatus(status:number) {
  11. return (status >= 200 && status < 300) || status === 400
  12. }
  13. }
  14. if (type.toLowerCase() === 'get') {
  15. option.params = data
  16. } else {
  17. option.data = data
  18. }
  19. axios(option).then((res: { status: number; data: unknown }) => {
  20. if(res.status === 200) {
  21. resolve(res.data)
  22. } else {
  23. reject(res.data)
  24. }
  25. }).catch(() => {
  26. console.error({msg: '网络异常'})
  27. reject({msg: '网络异常'})
  28. })
  29. })
  30. }

方法三

创建实例instance, 传入配置

  1. const instance = axios.create({
  2. baseURL: 'https://some-domain.com/api/',
  3. timeout: 1000,
  4. headers: {'X-Custom-Header': 'foobar'}
  5. });

之后再调用方法:instance.get/post/put/patch…