我有一个本地运行的Spring Backend,它具有以下端点:
@GetMapping(path = "/api/public/projects")
public Iterable<Project> findAllProjectsPublic(){
return projectRepository.findAll();
}
@GetMapping(path = "/api/private/projects/{id}")
public ResponseEntity<Project> findProjectById(@PathVariable Long id){
return projectRepository.findById(id)
.map(project -> ResponseEntity.ok().body(project))
.orElse(ResponseEntity.notFound().build());
}
@PostMapping(path = "/api/public/projects")
public Project createProject(@RequestBody Project project){
System.out.println(project);
return projectRepository.save(project);
}
当我在Postman中测试它们时,所有端点都按预期工作。
我在Angular中使用以下方法实现了服务:
public getAllProjects(cb) {
this.http.get<Project[]>(this.API_URL + "/public/projects")
.subscribe(projects => {
cb(null, projects);
}, error => {
cb(error, null);
})
}
public getProjectById(id: number, cb){
this.http.get<Project>(`${this.API_URL}/private/projects/${id}`)
.subscribe(project => {
cb(null, project);
}, error => {
cb(error, null);
})
}
public createProject(cb){
this.http.post(`${this.API_URL}/public/projects`, { name: 'Test'})
.subscribe(res => {
cb(null, res);
}, error => {
cb(error, null);
})
}
GET请求也可以在Angular中使用,但是POST请求不起作用,并写回带有错误消息的403状态:
Http failure response for (unknown url): 0 Unknown Error
当我在Spring中将Post Endpoint更改为接收字符串而不是我的@Request正文时,
@PostMapping(path = "/api/public/projects")
public Project createProject(String projectname){
return projectRepository.save(new Project("Test"));
}
有效!因此,它必须与请求正文有关。但是我仍然收到403禁止状态,这对我来说绝对没有意义。
我在邮递员中发送的尸体是:
{
"name": "Test"
}
那行得通...