Vue前后端分离实现登录的一个简单demo
程序员文章站
2022-07-10 12:43:56
...
1、建立一个Maven项目,并添加Spring相关依赖
2、编写Controller类相应的接口和配置类
LoginController类,编写接口的业务逻辑
package com.springboot.controller;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/login")
public class LoginController {
@RequestMapping(value = {"/login_submit"}, method = RequestMethod.POST)
public boolean login(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("abc") && password.equals("123456")) {
return true;
}
return false;
}
}
CorsConfig类,编写配置类用来解决跨域请求(接口是http,而axios一般请求的是https。从https到http是跨域,因此要配置跨域请求)
package com.springboot.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 解决跨域问题
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允许任何域名
corsConfiguration.addAllowedHeader("*"); //允许任何头
corsConfiguration.addAllowedMethod("*"); //允许任何方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注册
return new CorsFilter(source);
}
}
编写html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录</title>
</head>
<body>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 官网提供的 axios 在线地址 -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0-0/axios.min.js"></script>
<div id="app">
<input type="text" placeholder="请输入用户名" v-model="username" />
<br>
<input type="password" placeholder="请输入密码" v-model="password" />
<input type="button" v-on:click="login" value="登录" />
{{username}}
{{password}}
</div>
<script>
var app = new Vue({
el: "#app",
data: {
username: "",
password: ""
},
methods: {
login: function() {
let param = new URLSearchParams()
param.append('username', this.username)
param.append('password', this.password)
/*axios使用POST请求传参到接口http://localhost:8082/login/login_submit*/
axios({
method: 'post',
url: 'http://localhost:8082/login/login_submit',
data: param
}).then(
function(response) { //获取接口http://localhost:8082/login/login_submit的返回值
if (response.data == true) {
alert("登录成功");
} else {
alert("登录失败,用户名密码错误");
}
console.log(response);
},
function(err) {
alert("登录失败,用户名密码错误");
}
);
}
}
})
</script>
</body>
</html>
在Intellij Idea中启动Maven项目(即启动接口)
在HBuilder中启动html项目
上一篇: nginx制作检查配置bat文件
下一篇: nginx的详细配置