Vue-router hash模式微信登录授权验证,#号处理

14

Vue-router hash模式微信登录授权验证,#号处理

微信登录授权验证与 Vue-router hash 模式的兼容性

在使用 Vue-router 的 hash 模式时,微信登录授权验证可能会遇到一些问题。由于 hash 模式使用 URL 中的 号来表示路由,而微信登录授权验证会将 URL 中的 号去掉,这样就导致了 Vue-router 无法正确解析 Code。

问题描述

当用户在微信中点击登录按钮时,微信会跳转到一个授权页面,并且会将 Code传递给回调地址。由于使用 hash 模式,URL 中的 号会被去掉,这样就导致了 Vue-router 无法正确解析 Code。

解决方案

为了解决这个问题,我们可以在登录授权验证时检查 URL 是否包含 com/?code 这个关键字。如果包含,则证明是从微信跳转回来的。然后我们可以使用以下代码来处理 号:

```javascriptlet href = window.location.href;

if (href.includes("com/?code")) {

// url 包含 com/?code证明是从微信跳转回来的 let code = getParameterByName('code');

// 使用 code 进行登录授权验证 login(code);

} else {

// 不是从微信跳转回来的,直接跳转到首页 router.push('/');

}

```

getParameterByName() 函数

为了获取 URL 中的 Code,我们需要定义一个 getParameterByName() 函数:

```javascriptfunction getParameterByName(name) {

let url = window.location.href;

name = name.replace(/[[]/, "[").replace(/[]]/, "]");

var regex = new RegExp("[?&]" + name + "=([^&]*)");

var results = regex.exec(url);

return results === null ? "" : decodeURIComponent(results[1]);

}

```

login() 函数

在 login() 函数中,我们可以使用 Code 进行登录授权验证:

```javascriptfunction login(code) {

// 使用 code 进行登录授权验证 axios.post('/api/login', { code: code })

.then(response => {

console.log(response.data);

router.push('/');

})

.catch(error => {

console.error(error);

});

}

```

总结

通过以上的解决方案,我们可以在使用 Vue-router 的 hash 模式时,正确处理微信登录授权验证中的 号问题。

登录模式授权

版权声明:除非特别标注,否则均为网络文章,侵权请联系站长删除。

上一篇 Uniapp使用微信登录,获取的code been used或者invalid code错误解决方案

下一篇 结合若依框架实现微信小程序授权登录