在Controller里大概有这么个东西
@RestController
@RequestMapping("/system")
public class SystemController {
@Autowired
private SystemAPI system;
@GetMapping("/date")
public String getDbDate() {
return system.getDatabaseDate("yyyy-MM-dd HH:mm:ss");
}
}
然后在前台里有这么个东西
fetch("http://127.0.0.1:9090/system/date")
.then(res => res.text())
.then(res => {
console.log(res);
})
然后前台刷新一下,后台一看,调用了两次。
看了蛮多解释,大概是fetch在不做ContentType声明时get会请求两次,类似握手。
后面发现如果给fetch声明时post请求,或者后台返回的时候不是字符串,而是json就不会了,比如:
fetch("http://127.0.0.1:9090/system/date", {
method: 'post'
}).then(res => res.text()).then(res => {
console.log(res);
})
或者
@GetMapping("/date")
@ResponseBody
public HashMap<String, String> getDbDate() {
HashMap<String, String> retMap = new HashMap<>();
retMap.put("time", system.getDatabaseDate("yyyy-MM-dd HH:mm:ss"));
return retMap;
}
以上。