JavaScript 与 Spring RESTful API 通信需通过 fetch 发送 HTTP 请求,Spring 使用 @RestController 提供接口并配置 @CrossOrigin 解决跨域;前端用 GET 获取数据、POST 提交 JSON 数据需设置请求头 Content-Type 并序列化,PUT 更新、DELETE 删除资源,确保请求方法、数据格式正确即可实现完整交互。

JavaScript 与 Spring RESTful API 通信,主要是通过浏览器的 fetch API 或 AJAX 请求向后端暴露的 REST 接口发送 HTTP 请求(如 GET、POST、PUT、DELETE 等),Spring Boot 后端接收请求并返回 JSON 数据。下面一步步说明如何实现前后端通信。
在 Spring Boot 中,使用 @RestController 注解创建一个控制器,对外提供 JSON 格式的接口。
@RestController
@CrossOrigin(origins = "http://localhost:3000") // 允许前端域名访问(解决跨域)
public class UserController {
@GetMapping("/api/users")
public List<User> getUsers() {
return Arrays.asList(
new User(1, "Alice"),
new User(2, "Bob")
);
}
@PostMapping("/api/users")
public User createUser(@RequestBody User user) {
user.setId(99); // 模拟保存
return user;
}
}
注意: 必须添加 @CrossOrigin 或配置全局 CORS,否则浏览器会因同源策略拒绝请求。
使用 fetch() 从 Spring 接口获取用户列表:
fetch('http://localhost:8080/api/users')
.then(response => response.json())
.then(data => {
console.log('用户列表:', data);
// 可在此渲染到页面
})
.catch(error => console.error('请求失败:', error));
向后端提交新用户数据:
const userData = { name: "Charlie" };
fetch('http://localhost:8080/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(result => {
console.log('创建成功:', result);
})
.catch(error => console.error('提交失败:', error));
关键点: 设置 Content-Type: application/json,并用 JSON.stringify 序列化数据。
修改用户信息(PUT):
fetch('http://localhost:8080/api/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: "Alice Smith" })
})
.then(res => res.json())
.then(data => console.log('更新成功:', data));
删除用户(DELETE):
fetch('http://localhost:8080/api/users/1', {
method: 'DELETE'
})
.then(() => console.log('用户已删除'));
基本上就这些。只要 Spring 正确暴露 REST 接口,JS 使用 fetch 发送标准 HTTP 请求,就能实现完整通信。关键是处理好跨域、数据格式和请求方法。不复杂但容易忽略细节。
以上就是JS如何与SpringRESTfulAPI通信_JS与SpringRESTfulAPI通信的实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号