ITPub博客

首页 > 应用开发 > IT综合 > Vue与SpringBoot简单前后分离demo

Vue与SpringBoot简单前后分离demo

原创 IT综合 作者:lxz31102 时间:2021-01-21 05:31:06 0 删除 编辑

看了很多的资料,发现大家都是写Vue与SpringBoot简单前后分离demo,但目前我们保存用户状态时是需要token参与进来。

本文章仅介绍思路,具体实现代码会在一段时间后更新成一个开源框架供大家学习。

token,顾名思义,令牌。

而令牌需要谁发送,当然是检查的一方

所以下面我简单写一下关于前后端分离项目中,token的设计思路

1.在用户初次访问,检测是否存在token,如果不存在token,那么进行账户密码的校验,如果存在token,那么后台发送token到Vue前端,前端在localStorage中进行状态保存

2.由于Vue已经进行状态保存,所以每次获取用户信息时,只需要对Token里的信息进行提取即可

3.时效性,可以通过timeout设置超时时间,以此来控制账户的时效性保存

4.每次访问后端都需要把token放在请求头中,这样每次访问都可以判断token是否生效

5.如果不生效,跳转登录界面

要在之前解决掉跨域的问题

 

module.exports = {publicPath: '/admin',devServer: {port: 8080,disableHostCheck: true,proxy: {'^/api': {target: 'http://www.目标域名',changeOrigin: true, // 将主机标头的原点更改为目标URLpathRewrite: {'^/api': '/' //代理的路径}},}},}

 

首先我们说第一步,登录部分,沿用了上述我们第一部分的思路,先校验,后接收,再保存

onSubmit() {this.form.validateFields((err) => {if (!err) {this.logging = true;let code = this.form.getFieldValue("name");let password = this.form.getFieldValue("password");//记住我if (this.checked) {this.$store.dispatch("setLoginForm", {code: code,pass: password,checked: this.checked,});} else {this.$store.dispatch("setLoginForm", {});}// const encrypt = new JSEncrypt();// encrypt.setPublicKey(this.publicKey);// password = encrypt.encrypt(password);signIn({username: code,password: password,checkNum: this.form.getFieldValue("checkNum"),deviceId: this.deviceId,}).then((res) => {this.logging = false;if (res.rsCode == 0) {this.$ls.set("token", res.obj.token, 8 * 60 * 60 * 1000);this.$store.dispatch("保存位置", res.obj);this.$router.push("/路由位置");this.$notification["warning"]({message: "用户登录成功!",description: timeFix() + ",欢迎回来!",});} else {this.handleToggleCode();this.error = res.rsMsg;}});}});}

现在我们将3.4部合并,设置时效性,每次访问也都把token放在了头部

const service = axios.create({baseURL: BASE_URL, // api base_urltimeout: 60000, // 请求超时时间transformRequest: [function(data) {var ret = "";for (let it in data) {ret +=encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";}const token = Vue.ls.get("token");if (token) {ret += "token=" + encodeURIComponent(token);}return ret;},],});

最后只需要实现,token失效对其进行重新登录

const err = (error) => {if (error.response) {const data = error.response.data;const token = Vue.ls.get("token");if (error.response.status === 403) {notification.error({message: "拒绝访问",});}if (error.response.status === 401 &&!(data.result && data.result.isLogin)) {notification.error({message: "用户未授权",description: "用户登录超时,请重新登录!",});if (token) {//退出操作并转向登录页Vue.ls.clear();//这里我在路由当中是做了设定,如果token为空会进入到登录页,所以只需要清除即可}}}

 


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29797838/viewspace-2751582/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2014-08-09

  • 博文量
    10
  • 访问量
    5107