鍍金池/ 問答/HTML/ vue使用request獲取后端驗(yàn)證碼提示錯誤。

vue使用request獲取后端驗(yàn)證碼提示錯誤。

login.js代碼

export function getVerify() {
  return request({
    url: '/base/getVerify',
    method: 'get'
  })
}

index.vue代碼

<script>
import { getVerify } from '@/api/login'

export default {
  name: 'login',
  data() {
    return {
      verifyImg: ''
    }
  },
  methods: {
   .......
  },
  created() {
    getVerify().then(response => {
      this.verifyImg = response
    })
  }
}
</script>

我直接訪問http://a.com/base/getVerify 可以訪問到后端提供的驗(yàn)證碼
但是使用這種方法get后端驗(yàn)證碼地址,報錯(非跨域問題)

:9528/#/login:1 Uncaught (in promise) error

看了下header信息是GET沒錯,返回狀態(tài)也是200

Request URL: http://a.com/admin/base/getVerify
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:80
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: http://localhost:9528
Connection: Keep-Alive
Content-Length: 1211
Content-Type: image/png; charset=utf-8
Date: Sun, 25 Mar 2018 09:13:12 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.27 (Win64) PHP/7.1.9
X-Powered-By: PHP/7.1.9
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Host: a.com
Origin: http://localhost:9528
Referer: http://localhost:9528/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

驗(yàn)證碼無法顯示,請問是否需要修改什么?

<template>
  <div class="auth">
    <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm">
      <div class="panfish">
        <img :src="imgurl" :class="topimg"/>
      </div>
      <div class="panel">
        <h1 class="title">Sign IN</h1>
        <div class="input-group">
          <div class="input-box">
            <el-form-item prop="username">
              <el-input type="text" v-model="loginForm.username" auto-complete="off" placeholder="請輸入賬號" @focus="username()" @blur="none()"></el-input>
            </el-form-item>
          </div>
          <div class="input-box">
            <el-form-item prop="password">
              <el-input type="password" v-model="loginForm.password" auto-complete="off" placeholder="請輸入密碼" @focus="password()" @blur="none()"></el-input>
              <!--<span class="show-pwd" @click="showPwd"><svg-icon icon-class="eye" /></span>-->
            </el-form-item>
          </div>
          <div class="input-box">
            <el-form-item prop="verifyCode">
              <el-input type="verifyCode" v-model="loginForm.verifyCode" auto-complete="off" placeholder="請輸入驗(yàn)證碼" class="verifyCode"></el-input>
              <img :src="verifyUrl" @click="refreshVerify()" class="verify-pos"/>
            </el-form-item>
          </div>
        </div>
        <el-button type="primary" class="btn" v-loading="loading" @click.native.prevent="handleLogin">登錄</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getVerify } from '@/api/login'
import normal from '../../assets/images/normal.png'
import greeting from '../../assets/images/greeting.png'
import blindfold from '../../assets/images/blindfold.png'

export default {
  name: 'login',
  data() {
    return {
      imgurl: normal,
      topimg: 'normal',
      loginForm: {
        username: '',
        password: '',
        verifyCode: ''
      },
      verifyUrl: '',
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '請輸入賬號' }],
        password: [{ required: true, trigger: 'blur', message: '請輸入密碼' }],
        verifyCode: [{ required: true, trigger: 'blur', message: '請輸入驗(yàn)證碼' }]
      },
      verifyImg: '',
      loading: false,
      pwdType: 'password'
    }
  },
  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    refreshVerify() {
      this.verifyUrl = ''
      this.verifyUrl = this.verifyImg + '?v=' + window.moment().unix()
    },
    username: function() {
      this.imgurl = greeting
      this.topimg = 'greeting'
    },
    password: function() {
      this.imgurl = blindfold
      this.topimg = 'blindfold'
    },
    none: function() {
      this.imgurl = normal
      this.topimg = 'normal'
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('Login', this.loginForm).then(() => {
            this.loading = false
            this.$router.push({ path: '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  created() {
    getVerify().then(response => {
      this.verifyImg = response
    })
    this.verifyUrl = this.verifyImg
  }
}
</script>
回答
編輯回答
我甘愿

問題分析

這是一個很好的問題。

  • created 鉤子中,verifyImgthen 內(nèi)賦值,但 verifyUrl 卻在 then 外賦值,這會導(dǎo)致 verifyUrl 賦值早于 verifyImg。你可以在這兩個賦值語句上分別打個斷點(diǎn),看下哪個先執(zhí)行,然后加深一下對 promise、異步的理解。
getVerify().then(response => {
  this.verifyImg = response
})
this.verifyUrl = this.verifyImg // 這一句會早于 promise then 中的賦值語句執(zhí)行
  • @廈冰 的回答下你的評論中,提到前后端分離,以及你在 dev.env.js 定義后端地址。前后端分離的一個比較便利的開發(fā)實(shí)踐是使用 proxy 將請求中當(dāng)前 dev server 下的相對路徑代理為后端路徑,你可以直接通過 Vue cliwebpack 項(xiàng)目模板來學(xué)習(xí)如何設(shè)置和使用 proxyVue cli webpack 項(xiàng)目模板文檔 API Proxying During Development。如果不使用代理,即使在 dev.env.js 中定義了后端地址,你的相對路徑請求仍然會發(fā)送到 dev server,這大概是 Uncaught (in promise) error(估計(jì)是一個 404 錯誤,因?yàn)槟銓?shí)際發(fā)起的請求指向了 localhost)產(chǎn)生的原因。
  • AJAX 請求的本質(zhì)。AJAX 是發(fā)起一個請求并獲取其響應(yīng),因此當(dāng)你去請求 /base/getVerify 時,如果沒有發(fā)生Uncaught (in promise) error,實(shí)際獲取的是后端對這個請求的響應(yīng),這里是一個圖片文件的內(nèi)容。
  • img src 屬性的取值。imgsrc 屬性是一個圖片地址,因此,這個屬性可以設(shè)置為一個 url 路徑,或者是一個 dataURL,正如 @minororange 的回答中建議的,你可以在 /base/getVerify 響應(yīng)中返回一個 base64 dataURL。但這個屬性不應(yīng)該設(shè)置為一個圖片文件的內(nèi)容,即使你在這里使用了代理,如果返回的內(nèi)容不是一個 dataURL,才可以直接將 src 綁定到 verifyUrl。
  • 驗(yàn)證碼的刷新。refreshVerify 組件方法本身沒問題,但當(dāng)一個路徑是一個 圖片文件內(nèi)容 + queryString 的時候,錯誤是明顯的。
  • 調(diào)試技巧。當(dāng) Uncaught (in promise) error 錯誤發(fā)生時,開發(fā)者工具中一定還有更為有用的信息可供參考,你需要去找到它、學(xué)會分析。

建議的解決方案

首先需要設(shè)置開發(fā)代理,具體參考 Vue cli webpack 項(xiàng)目模板文檔。

在設(shè)置好開發(fā)代理的前提下,可以根據(jù)上面的分析來解決問題,有如下兩個途徑:

  1. dataURL。即 @minororange 回答中建議的方法。但需要后端配合,修改驗(yàn)證碼請求返回的結(jié)果,相應(yīng)的 refreshVerify 方法也要修改。
  2. 直接在組件數(shù)據(jù)中設(shè)置 verifyUrl 初始值為 '/base/getVerify?v=' + window.moment().unix(),不需要 created 鉤子進(jìn)行初始化,然后在 refreshVerify 組件方法中重設(shè)(咦?)為 this.verifyUrl = '/base/getVerify?v=' + window.moment().unix()
data() {
  return {
    // ... 
    verifyUrl: '/base/getVerify?v=' + window.moment().unix()
  },
},
methods: {
  refreshVerify() {
    this.verifyUrl = '/base/getVerify?v=' + window.moment().unix()
  },
  // ...
}
2017年6月27日 15:44
編輯回答
笨笨噠

Content-Type: image/png; charset=utf-8后端返回的是個圖片,前端怎么處理的,應(yīng)該是用一個img標(biāo)簽,把img的src指向這個api吧

2018年8月6日 09:19
編輯回答
墨小羽

讓后端將圖片轉(zhuǎn)成base64格式的src字符串 丟到img標(biāo)簽的src中就可以了

data:image/png;base64,xxxxxxxxxxxxxxx

2018年6月28日 01:28