JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。AngularJS 是一个前端 JavaScript 框架,用于构建单页应用程序。Spring Boot 是一个用于简化 Spring 应用程序初始搭建以及开发过程的框架,其中的 RestController 用于处理 RESTful Web 服务请求。
@RequestBody
来接收前端发送的 JSON 数据。在现代 Web 开发中,前端框架(如 AngularJS)与后端服务(如 Spring Boot)之间的数据交换通常使用 JSON 格式进行。
当 JSON 数据从 AngularJS 传递到 Spring Boot RestController 不起作用时,可能的原因包括:
Content-Type: application/json
。@RequestBody
注解来接收 JSON 数据。在 AngularJS 中发送 POST 请求时,确保设置了正确的请求头:
$http({
method: 'POST',
url: '/api/data',
data: JSON.stringify(yourData),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
// 处理成功响应
}, function(error) {
// 处理错误响应
});
确保发送的 JSON 数据格式正确,并且与后端接收的数据模型匹配。例如,如果后端期望一个包含 name
和 age
的对象,前端发送的数据应该是:
{
"name": "John",
"age": 30
}
@RequestBody
注解在 Spring Boot 的 RestController 中,使用 @RequestBody
注解来接收 JSON 数据:
@RestController
@RequestMapping("/api")
public class DataController {
@PostMapping("/data")
public ResponseEntity<?> receiveData(@RequestBody YourDataModel data) {
// 处理接收到的数据
return ResponseEntity.ok().build();
}
}
如果前端和后端不在同一个域上,可以在 Spring Boot 中配置 CORS:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
}
通过以上步骤,你应该能够解决 JSON 数据从 AngularJS 传递到 Spring Boot RestController 不起作用的问题。
领取专属 10元无门槛券
手把手带您无忧上云