请求说明

  1. // /根目录/api/index.js 基于第三方库uni-network封装(简介上面有文档地址)
  2. # 发送get请求
  3. uni.$http.get('/api/home/getBanner').then(res => {
  4. }).catch(err => {
  5. })
  6. # 发送post请求
  7. uni.$http.post('/api/home/getBanner', {
  8. }).then(res => {
  9. }).catch(err => {
  10. })
  11. # 图片上传
  12. uni.chooseImage({
  13. count: 1,
  14. sizeType: ['original', 'compressed'],
  15. sourceType: ['album', 'camera'],
  16. success: res => {
  17. uni.$http.upload({
  18. url: '/api/file.File/add',
  19. formData: {
  20. type: 'upl',
  21. file_type: 'image'
  22. },
  23. file: res.tempFiles[0]
  24. }).then(res => {
  25. if (res.code === 200) {
  26. // 处理业务逻辑
  27. }
  28. })
  29. }
  30. })

自定义请求

如果您有自定义请求头或者其他方便的需求,可以直接修改/api/index.js,如下

  1. // /api/index.js
  2. instance.interceptors.request.use(
  3. function (config) {
  4. const userStore = useUserStore()
  5. // 传递语言code给后端
  6. if (config.url.indexOf('?') !== -1) {
  7. config.url = `${config.url}&lang=${userStore.languageCode}`
  8. } else {
  9. config.url = `${config.url}?lang=${userStore.languageCode}`
  10. }
  11. if (config.data && config.data.withoutToken) {
  12. return config
  13. }
  14. config.headers.apitoken = uni.getStorageSync('token')
  15. config.headers.key = `adsadasd`
  16. return config
  17. }
  18. )