我试图将vue.js与Spring Boot集成在一起。这是我的vue.js代码:
<template>
// ...
</template>
<script>
export default {
name: "Login",
data: function() {
return {
username: '',
password: '',
msg: ''
}
},
methods: {
// post data to Spring Boot
login() {
axios.post('/login',{
username: this.username,
password: this.password
})
.then(function(response) {
if(response.data.code === 200){
this.$store.dispatch('setCurrentUser',this.username);
// vue-route
this.$router.push('/course');
} else {
this.msg = response.message;
}
})
.catch(function(err) {
this.msg = 'error';
});
}
}
};
</script>
这是我的Spring Boot控制器:
@RestController
@ResponseBody
public class LoginController {
@Autowired
private ResultGenerator resultGenerator;
@PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
return resultGenerator.getSuccessResult();
} else {
return resultGenerator.getFailResult("error");
}
}
}
控制器将返回类似于以下内容的JSON数据:{"code":200,"message":"success","data":null}
。调用login
方法时,控制器可以接受用户名和密码,并且控制器也发送响应数据。但是,仅此而已,vue-router无效。我在浏览器中看到的是:
有人可以帮忙吗?
------------------添加-----------------------
这是vue-router配置:
const routes = [
{
path: '/',
component: Login
},
{
path: '/signin',
component: Signin
},
{
path: '/course',
component: Course
}
];
const router = new VueRouter({
routes,
mode: "history"
});
答案 0 :(得分:0)
问题可能是您返回resultGenerator.getSuccessResult()。您是否尝试过重定向到Spring Boot Controller内部的'/ course'路径?
@PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
this.$router.push('/course');
} else {
return resultGenerator.getFailResult("error");
}
}
答案 1 :(得分:0)
如果Vue.js和Spring boot是2个不同的应用程序(例如后端和前端),则可能会有所帮助:
尝试在您的@controller或用于公开其余内容的方法上使用@CrossOrigin(CORS),在Ionic 3 proyect上也遇到了类似的问题,那可以解决问题。
示例:
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
它应该看起来像这样:
@RestController
@ResponseBody 公共类LoginController {
@Autowired
private ResultGenerator resultGenerator;
@CrossOrigin(origins = "http://localhost:9000") // The IP:PORT of the vue app origin
@PostMapping("/login")
public RestResult login(String username, String password){
if(username.equals("123") && password.equals("123")){
return resultGenerator.getSuccessResult();
} else {
return resultGenerator.getFailResult("error");
}
}
}