在本地主机上使用 spring api 获取失败
failed to fetch using spring api on localhost
javascript 尝试从我的 spring 引导 api 获取数据,但每次都返回“获取失败”错误。
我确定请求到达 api 因为每次点击提交我都会得到打印语句,我将其放入我的 get 方法中,并按应有的方式记录。所以回来的路上一定是出了什么问题。
获取方法:
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
private FamilyRepository familyRepository;
public FamilyController(FamilyRepository familyRepository) {
this.familyRepository = familyRepository;
}
@GetMapping("/id/{id}")
public FamilyMember getById(@PathVariable("id") Long id) {
Optional<FamilyMember> optional = familyRepository.findById(id);
if (!optional.isPresent()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
FamilyMember familyMember = optional.get();
System.out.println(id); //print statement to make sure api is reached
return familyMember;
}
Javascript代码:
const url = 'http://localhost:4001/familyMember/';
submit.onclick = async() => {
const endpoint = url + 'id/' + input.value;
try {
const response = await fetch(endpoint); // error occures here because no code below is executed
output.style.color = 'green'; // to see if fetch continues(apparently it doesn't)
if (response.ok) {
output.innerHTML += await response.json();
}
} catch(error) {
output.innerHTML += error; // gives me "Failed to fetch" in the html
}
我不确定错误是在服务器端还是客户端。当我在终端中使用 curl 时,api 为我提供了正确的信息……那么可能是 js 代码?
提前致谢。
居然找到了答案。在@RestController 上方,我需要注解 @CrossOrigin
以便 api 允许来自不同来源的请求(在这种情况下是 html 文件)。
@CrossOrigin
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
...
javascript 尝试从我的 spring 引导 api 获取数据,但每次都返回“获取失败”错误。
我确定请求到达 api 因为每次点击提交我都会得到打印语句,我将其放入我的 get 方法中,并按应有的方式记录。所以回来的路上一定是出了什么问题。
获取方法:
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
private FamilyRepository familyRepository;
public FamilyController(FamilyRepository familyRepository) {
this.familyRepository = familyRepository;
}
@GetMapping("/id/{id}")
public FamilyMember getById(@PathVariable("id") Long id) {
Optional<FamilyMember> optional = familyRepository.findById(id);
if (!optional.isPresent()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
FamilyMember familyMember = optional.get();
System.out.println(id); //print statement to make sure api is reached
return familyMember;
}
Javascript代码:
const url = 'http://localhost:4001/familyMember/';
submit.onclick = async() => {
const endpoint = url + 'id/' + input.value;
try {
const response = await fetch(endpoint); // error occures here because no code below is executed
output.style.color = 'green'; // to see if fetch continues(apparently it doesn't)
if (response.ok) {
output.innerHTML += await response.json();
}
} catch(error) {
output.innerHTML += error; // gives me "Failed to fetch" in the html
}
我不确定错误是在服务器端还是客户端。当我在终端中使用 curl 时,api 为我提供了正确的信息……那么可能是 js 代码?
提前致谢。
居然找到了答案。在@RestController 上方,我需要注解 @CrossOrigin
以便 api 允许来自不同来源的请求(在这种情况下是 html 文件)。
@CrossOrigin
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
...