在SpringBoot项目中,默认使用嵌入式Tomcat作为Web服务器,前端JS可以直接通过HTTP请求访问控制器暴露的接口,完成数据交互。这种方式省去了单独部署服务器的步骤,非常适合中小型应用和快速验证。

一、SpringBoot后端接口准备
首先创建一个简单的控制器,使用@RestController和@RequestMapping暴露接口。嵌入式服务器启动后,默认监听8080端口。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// 暴露GET接口,路径为 /api/hello
@GetMapping("/api/hello")
public String sayHello(@RequestParam String name) {
return "你好, " + name + ", 来自嵌入式服务器的响应";
}
}
二、前端JS调用方式
前端可以使用浏览器原生的fetch函数,向SpringBoot嵌入式服务器发送请求。假设服务运行在127.0.0.1:8080,代码如下:
// 调用SpringBoot接口
fetch('http://127.0.0.1:8080/api/hello?name=张三')
.then(function(response) {
return response.text();
})
.then(function(data) {
// 将返回内容写入页面
document.getElementById('result').innerText = data;
})
.catch(function(err) {
console.error('请求失败:', err);
});
使用axios简化请求
如果项目中引入了axios库,也可以用更简洁的写法完成调用:
axios.get('http://127.0.0.1:8080/api/hello', {
params: { name: '李四' }
}).then(function(res) {
console.log(res.data);
});
三、跨域问题处理
当前端页面与SpringBoot服务不在同一源时,浏览器会阻止请求。可以在后端添加@CrossOrigin注解开放跨域:
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500")
public class UserController {
@GetMapping("/api/user")
public String getUser() {
return "用户数据";
}
}
四、注意事项
- 确认嵌入式服务器端口未被占用,可在application.properties中修改server.port。
- 前端调用时应使用正确的HTTP方法,与后端映射一致。
- 返回JSON数据时,SpringBoot会自动序列化对象,前端用response.json()解析即可。
前端JS调用SpringBoot嵌入式服务器,本质就是标准的HTTP客户端与HTTP服务端通信,只要接口路径和跨域配置正确,就能稳定获取数据。
SpringBoot嵌入式服务器前后端交互修改时间:2026-07-26 08:06:16