Java Spring Controller 拒绝除 GET 之外的所有请求

标签 java angular spring cors

我正在 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/

相关文章:

java - 在另一个 Activity 中显示选定的图像

html - 具有自定义宽度的 PrimeNG TurboTable 无法正常工作

java - 如何指定除一条之外的所有路线?

java - Maven 故障安全插件不运行并行测试

java.lang.VerifyError : Stack shape inconsistent

javascript - 除某些点击事件外,Mat-Menu 上的 StopPropagation - Angular

angular - 选择上的 ngModel 不显示初始值、默认值

java - 尽管组件位于同一包和扫描组件中,但 Spring 未检测到该组件

Spring循环依赖使用setter

java - azure 函数在 IntelliJ IDEA 中调试错误