我是Sping Boot、rest api和angular12的新手,
我在vscode中运行我的程序来调用后台api,我得到了错误消息"Failed to load resource: the server responded with a status of 404 (Not Found)“。
我的代码:后端控制器:
@RestController
@RequestMapping("/evaluationController/")
public class EvaluationController {
@Autowired
private EvaluationRepository evaluationrepository;
//get all evaluationsnotes
@CrossOrigin(origins = "http://localhost:4200/")
@GetMapping("/notes")
public List<EvaluationModel> getAllEvaluations(){
return evaluationrepository.findAll();
}
//post notes
@PostMapping("/notes")
public EvaluationModel createEvaluationNote(@RequestBody EvaluationModel evaluationNote) {
return evaluationrepository.save(evaluationNote);
}
}我的前端angular12服务
@Injectable({
providedIn: 'root'
})
export class EvaluationserviceService {
private baseUrl!: "http://localhost:8080/evaluationController/notes";
constructor(private httpClient: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getEvaluationNotes():Observable<Evaluationotes[]>{
return this.httpClient.get<Evaluationotes[]>(`${this.baseUrl}`);
}
}我的typescript文件
@Component({
selector: 'app-fin-evaluation',
templateUrl: './fin-evaluation.component.html',
styleUrls: ['./fin-evaluation.component.css']
})
export class FinEvaluationComponent implements OnInit {
evaluationNote!: Evaluationotes[];
constructor(private evaluationNoteService: EvaluationserviceService ) { }
ngOnInit(): void {
this.getAllNotes();
}
private getAllNotes(){
this.evaluationNoteService.getEvaluationNotes().subscribe(data=>{
this.evaluationNote = data;
});
}
}谢谢!
发布于 2021-06-13 17:07:55
问题出在baseUrl,您需要使用= (用于初始化)而不是: (在typescript中用于定义对象类型)。由于您从未真正使用正确的url初始化变量,因此请求将发送到某个随机url,如http://localhost:4200/undefined,从而导致404。您可以按如下方式更新url,然后尝试:
private baseUrl = "http://localhost:8080/evaluationController/notes";https://stackoverflow.com/questions/67942767
复制相似问题