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

The interface has a return value, but the axios report response is undefined #6316

Open
JavaDevelopeZ opened this issue Mar 24, 2024 · 2 comments

Comments

@JavaDevelopeZ
Copy link

Describe the bug

my interface data format:
return R(status='error', message='端口被占用,请换一个吧', code=200, data={"data": port}).to_json()
When code=200, it is normal. When code=201, the browser network can receive data, but the axios response is undefined. All other interfaces in the project are normal.

To Reproduce

No response

Code snippet

python code:
 try:
            form_data = request.get_json()
            print(form_data)
            port = form_data.get('port', None)
            if port is None:
                return R(status='error', message='端口为空!', code=200).to_json()
            result = scan_ports(config.SSH_HOST_IP, port)
            if result is True:
                return R(status='success', message='端口可用', code=200, data={"data": port}).to_json()
            elif result is False:
                return R(status='error', message='端口被占用,请换一个吧', code=201, data={"data": port}).to_json()
        except Exception as e:
            current_app.logger.error(f'{e}')
            return R(status='error', message='请求失败', code=201).to_json()




vue code:
validateIt() {
      const t = this
      t.isLoading = true
      jiaoyan(t.form)
        .then(res => {
          if (res && res.code === 200) {
            t.$message(
              {
                message: res.message,
                type: 'success'
              }
            )
            t.btnEnable = false
            t.isLoading = false
          } else {
            t.$message(
              {
                message: res.message,
                type: 'error'
              }
            )
            t.btnEnable = true
            t.isLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          t.btnEnable = true
          t.isLoading = false
          console.log('--------------***************-----------')
        })

Encapsulated requests:
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 是否显示重新登录
export const isRelogin = { show: false }
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests  跨域请求发送cookie
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()// 让每个请求携带自定义token,原来没有前缀
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // const msg = errorCode[res.code] || res.message || errorCode['default']

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // Message({
      //   message: res.message || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      // return Promise.reject(new Error(res.message || '后端接口异常'))
      // eslint-disable-next-line no-unreachable
      if (response.data.code === 401) {
        if (!isRelogin.show) {
          isRelogin.show = true
          MessageBox.confirm('登录状态已过期,请重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            isRelogin.show = false
            // store.dispatch('logout')
            this.$router.push('/login')
            // return Promise.reject(msg)
          }).catch((status) => {
            isRelogin.show = false
          })
        }
      }
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code 401')) {
      message = '登录会话超时,请重新登录'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service

Expected behavior

When code=201, the else branch should be used instead of restocking. Res is undefined.
IMG_1293(20240324-112511)

Axios Version

0.18.1

Adapter Version

HTTP

Browser

FireFox

Browser Version

124

Node.js Version

14.9.0

OS

Windows 11

Additional Library Versions

VUE:2

Additional context/Screenshots

No response

@misakamayako
Copy link

在你的拦截器内,if没有匹配到任何状态码的情况下,也应该返回res

@JavaDevelopeZ
Copy link
Author

在你的拦截器内,if没有匹配到任何状态码的情况下,也应该返回res

是的,但是当自定义code为201的时候,拦截器中是有res的,但是到了vue页面中,.then以后,里面的response对象就变成undefined了,拦截器中的res是有数值的,自定义code为200的时候是正常的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants