我正在Angular上使用前端开发Java Spring应用程序,但是我遇到的问题是没有您的帮助我无法解决。当我从Angular向Java发出请求时,只有GET请求正在传递,但POST,DELETE和POST返回以下错误
已从CORS策略阻止从原点[http://localhost:8080/patient'访问'http://localhost:4200处XMLHttpRequest:在所请求的资源上没有'Access-Control-Allow-Origin'标头。
控制者
@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 service
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
}
}
谢谢你!
不需要在origins=*
批注中设置@CrossOrigin
,默认情况下允许所有原点。
您试图将注释置于方法级别?