我正在 Angular 上使用前端开发 Java Spring 应用程序,但我遇到了如果没有您的帮助我无法解决的问题。当我从 Angular 向 Java 发出请求时,仅传递 GET 请求,但 POST、DELETE 和 POST 返回以下错误
Access to XMLHttpRequest at 'http://localhost:8080/patient' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Controller
@Controller
@RequestMapping("/patient")
@CrossOrigin(origins = "*", maxAge = 3600)
public class PatientController {
private PatientService patientService;
@Autowired
public PatientController(PatientService patientService) {
this.patientService = patientService;
}
@GetMapping
public ResponseEntity<Iterable<Patient>> getPatient() {
return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Iterable<Patient>> postPatient() {
return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
}
@PutMapping
public ResponseEntity<Iterable<Patient>> putPatient() {
return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<Iterable<Patient>> deletePatient() {
return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
}
}
Angular 服务
getPatients() {
this.http.post(AppComponent.apiUrl + '/patient', this.httpOptions)
.subscribe(data => {
console.log(data);
});
}
proxy.conf.json
{ "/api*": {
"target":"http://localhost:8080",
"secure":false,
"logLevel":"debug",
"changeOrigin": true
}
}
提前谢谢您!
最佳答案
不需要在@CrossOrigin
注解中设置origins=*
,默认允许所有来源。
您尝试将注释放在方法级别吗?
关于Java Spring Controller 拒绝除 GET 之外的所有请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61104834/