gpt4 book ai didi

javascript - 如何使用 Vue.js 将用户登录到 spring-security 应用程序?

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:55 24 4
gpt4 key购买 nike

嗨,这是我关于堆栈溢出的第一篇文章。我想将后端与前端分离,并使用我的 Spring Boot 应用程序创建 REST API。我使用 spring-security 登录。它使用名为 JSESSION_ID 的东西,但如何使用 Vue.js 登录和授权用户?我想制作用于登录我的服务的表单并使用 JSESSION_ID 授权请求。

这是我在 Vue.js 中的第一个应用程序。我尝试使用教程和文档中的代码,但它没有解决我的问题。我也有 CORS 问题。

    export default {
name: 'Login',
data(){
return{
username: '',
password: '',
error: false
}
},
updated(){
if (localStorage.token){
this.$router.replace(this.$route.query.redirect || '/')
}
},
methods:{
login(){
this.$http.post('http://localhost:8080/login', { username: this.username, password: this.password })
.then(request => this.loginSuccessful(request))
.catch(() => this.loginFailed())
},
loginSuccessful (req) {
if (!req.data.token) {
this.loginFailed();
return
}
this.error = false;
localStorage.token = req.data.token;
this.$router.replace(this.$route.query.redirect || '/')
},
loginFailed () {
this.error = 'Login failed!';
delete localStorage.token
}
}
}

我希望使用 REST Spring-Boot API 从 Vue.js 登录并授权用户。

最佳答案

问题是您尝试传递对象 { username: this.username, password: this.password }作为请求的数据,但您没有指定 Content-Type,它可能默认为“text/html”或“application/json”。您可以尝试先将其转换为表单数据,然后将其传递给请求,这里是 AXIOS 的示例:

login() {
let formData = new FormData();
formData.set("username", this.username);
formData.set("password", this.password);
AXIOS.post('/login', formData, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((result) => {
this.loginSuccessful(result);
})
.catch((error) => {
this.loginFailed();
})
}

也许在不指定 header 的情况下它也可以工作,例如 AXIOS.post('/login', formData, null) ,没试过。

关于javascript - 如何使用 Vue.js 将用户登录到 spring-security 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57207183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com