场景
项目中使用nuxt开发一个表单,图片验证码接口提供一个通过http get请求png二进制流,接口请求使用的nuxt/http。 版本信息如下
"@nuxt/http": "^0.6.4",
"nuxt": "^2.15.8",
接口/api/captcha/code返回的png二进制流,如下
使用 image src 方式
根据多年经验,可以将get api直接放入image src属性里,通过点击切换captchaKey实现图片验证码刷新
nuxt.config.js 启用代理
modules: [
"@nuxt/http",
],
http: {
proxy: true
},
proxy: {
'/api': {
target: 'http://xxxxx',
pathRewrite: {
'^/api': '/api'
}
}
},
html 部分
<img :src="captchaImageUrl" @click="onChangeCaptcha"/>
js 部分
data() {
return {
captchaKey: '',
captchaImageUrl: '',
}
},
mounted() {
this.onChangeCaptcha();
},
methods: {
onChangeCaptcha: function () {
this.captchaKey = `${new Date().getTime()}`;
this.captchaImageUrl = `/api/captcha/code?key=${this.captchaKey}`;
},
}
补充nuxt.config.js使用@nuxtjs/axios配置代理方式
axios: {
proxy: true,
},
proxy: {
'/api': {
target: 'http://xxxxx',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
},
@nuxt/http 不使用代理
接下来刨坑经历的开始,nuxt.config.js没有使用启用代理
nuxt.config.js 配置
modules: [
"@nuxt/http",
],
http: {
baseURL: "http://xxxxx"
},
调整js 部分
methods: {
onChangeCaptcha: async function () {
this.captchaKey = `${new Date().getTime()}`;
this.captchaImageUrl = `/api/captcha/code?key=${this.captchaKey}`;
},
}
然后控制台报错。image src获取不到图片。
于是换个思路是通过responseType制定返回数据格式为blob,然后通过window.URL.createObjectURL生成Url。nuxt/http掉坑开始 \
调整js 部分
methods: {
onChangeCaptcha: async function () {
this.captchaKey = `${new Date().getTime()}`;
const response = await this.$http.$get(`get/captcha/code?key=${this.captchaKey}`,
{ responseType: "blob" });
this.captchaImageUrl = window.URL.createObjectURL(response);
},
}
通过网上查询结果说是需要new Blob(),于是修改window.URL.createObjectURL(new Blob([response],{type: "image/jpeg"}))
于是开始翻阅nuxt/http的文档说明,
没有找到关于responseType: "blob"相关内容
如果有网友知道的可以留言回复一下这个的解决方式
@nuxtjs/axios 不使用代理
根据网上查阅的资料,vue 中使用axios应该是可以responseType: "blob"来实现转化的。于是修改项目使用@nuxtjs/axios进行测试。
调整js 部分
methods: {
onChangeCaptcha: async function () {
this.captchaKey = `${new Date().getTime()}`;
const response = await this.$axios.$get(`get/captcha/code?key=${this.captchaKey}`,
{ responseType: "blob" });
this.captchaImageUrl = window.URL.createObjectURL(response);
},
}
\
【继续刨坑】表单提交始终验证图片验证码不正确
和后端沟通校验机制:获取图片验证码的接口将图片验证码whkw拼到ssesion中,提交表单的时在通过ssesion进行校验。
初步猜想axios的ssesion不固定导致的,这里没有进行猜想尝试验证。
采用了第二种方案利用captchaKey的值代替ssesion校验,获取图片验证码的接口传递captchaKey给后端,提交表单的时也带上captchaKey进行校验。
小结
这是一个看似简单的问题的埋坑经历,欢迎评论留言发表自己的看法。