我正在使用 java springboot 和 Angular 7 开发聊天应用程序。我在 spring boot 和 Angular 中使用事件。我正在尝试在 Spring Boot 中生成事件,以便 Angular 监听该事件。但是,我收到以下错误:
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
这是我在 springboot 中的 Controller 代码:
@CrossOrigin("*")
@RestController
@RequestMapping("/chat")
public class MessageController {
@Autowired
MessageService messageService;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
@PostMapping(consumes = "application/json", produces = "application/json")
public GenericApiResponse<Map<String, Object>>message(@RequestBody MessageRequest req) {
logger.info("MessageController:: messagemethod [POST] /chat");
GenericApiResponse<Map<String, Object>> responseObj = new GenericApiResponse<>();
Object returnValue = new Object();
try {
returnValue = messageService.translateText(req);
} catch (Exception e) {
e.printStackTrace();
logger.error("EXCEPTION: "+e.getStackTrace().toString());
responseObj.setStatus(Constants.ERROR);
responseObj.setMessage("Internal Server Error");
}
Map<String, Object> resMap = new HashMap<>();
resMap.put("result", returnValue);
resMap.put("sender", req.getSender());
responseObj.setResponseObject(resMap);
responseObj.setStatus(Constants.SUCCESS);
MessageEvent messageEvent = new MessageEvent(this,"eventName", responseObj);
applicationEventPublisher.publishEvent(messageEvent);
return responseObj;
}
我无法弄清楚问题是什么以及如何解决。请帮我解决这个问题。 预先感谢:)
最佳答案
从第一眼看你的代码,我可以观察到以下问题:
@ResponseBody
已添加,但未返回任何响应,即方法类型为 void。products = "application/json"
对于不返回响应的 void 方法没有意义。
因此,对于休息端点总是返回一些响应。您可以通过将以下作为返回语句放在方法的末尾来修复它:
return ResponseEntity.ok("your message");
此外,@ResponseBody
意味着响应始终序列化为 json,因此无需显式指定 , Produces = "application/json"
。
更新:
您能否尝试将 consumes = "application/json", Produces = "application/json"
替换为
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
还有
确保请求 header 设置为 application/json
。
此外,ensrue jackson 依赖项已就位。
关于java - org.springframework.web.HttpMediaTypeNotAcceptableException : Could not find acceptable representation in java spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58498344/