前端访问后端接口
前端写法:
<!DOCTYPE html>
<html>
<head>
<title>注册</title>
<meta charset="utf-8">
</head>
<body>
<h1>注册</h1>
<form method="post" action="" id="register-form">
<div>
<label for="username">用户名:</label>
<input type="text" name="username" id="username" required>
</div>
<div>
<label for="password">密码:</label>
<input type="password" name="password" id="password" required>
</div>
<div>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" required>
</div>
<div>
<label for="telephone">电话:</label>
<input type="text" name="telephone" id="telephone" required>
</div>
<div>
<input type="submit" value="注册">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const registerForm = document.getElementById('register-form');
registerForm.addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const email = document.getElementById('email').value;
const telephone = document.getElementById('telephone').value;
// 使用jQuery发送POST请求将用户信息提交到后端API服务进行注册
$.ajax({
url: 'http://localhost:8080/user/register',
method: 'GET',
data: { username, password, email ,telephone},
success: function(response) {
window.location.replace("login.html");
alert('注册成功!');
},
error: function(xhr) {
alert('注册失败:' + xhr.responseText);
}
});
});
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
ws: true,
changeOrigin: true
}
}
}
}
</script>
</body>
</html>```
后端写法:
加一个跨域的配置类
package org.example.config;
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;
import java.time.Duration;
/**
-
添加支持跨域
*/
@Configuration
public class GlobalCorsConfig {@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin(““);
//是否发送 Cookie
config.setAllowCredentials(true);
//放行哪些请求方式
config.addAllowedMethod(””);
//放行哪些原始请求头部信息
config.addAllowedHeader(“*”);
config.setMaxAge(Duration.ofHours(6));
config.addExposedHeader(“Content-Type”);
config.addExposedHeader(“X-Requested-With”);
config.addExposedHeader(“accept”);
config.addExposedHeader(“Origin”);
config.addExposedHeader(“Access-Control-Request-Method”);
config.addExposedHeader(“Access-Control-Request-Headers”);
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration(“/**”, config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
}
software文件夹下面的ununite文件夹下面。