【问题标题】:Cross Origin Issue in Spring Boot and Angular ApplicationSpring Boot 和 Angular 应用程序中的跨域问题
【发布时间】:2021-10-13 03:14:44
【问题描述】:

好吧,我必须将 Spring 与 Angular 集成,以实现这个我得到 Cross Policy 问题,为此我已经在 Rest 控制器中添加了 @CrossOrigin 注释。 下面是我的代码

我的休息控制器

@RestController
@CrossOrigin(origins = {"http://localhost:9001", "http://localhost:4200"},allowedHeaders = "*")
public class PatientVisitRestController {
    
    @Autowired
    PatientVisitService patientVisitService;
    
    
    @PostMapping("/patient/add")
    public String savePatientVisit(@RequestBody PatientVisit patientVisit)
    {
        
        patientVisitService.addPatientVisit(patientVisit);
        
        return "Saved := "+patientVisit.getPatientName()+" - "+patientVisit.getSlipNumber();
        
    }

    @GetMapping("/patient/phone/{ph}")
    public List<PatientVisit> getPatientbyPhone(@PathVariable long ph)
    {
        List<PatientVisit> list =  patientVisitService.getPatientVisitByPhoneNumber(ph);
        return list;
    }
    
    
    
}  //end controller


@SpringBootApplication
public class OpdPatientConsoleApplication {

    public static void main(String[] args) {
        SpringApplication.run(OpdPatientConsoleApplication.class, args);
    }

}

下面是我的 Angular 服务

import { PatientDetails } from './patient-details';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PatientService {

  contextPath:string= 'http://localhost:9001';
  // tomcatServerContentRoot = 'http://localhost:8081';
  endPoint_getPatientsByPhone:string =  this.contextPath+'/patient/phone/';
  
 
  http:HttpClient;
     
  constructor(http:HttpClient) {
    this.http = http;
  }

  getPatientsByPhone(phone:number):Observable<PatientDetails[]>
  {
    let endPoint_getPatientsByPhone = this.contextPath+'/patient/phone/'+phone;
    console.log("--->> Patient Service : searchPatientsByPhone endpoint :- "+endPoint_getPatientsByPhone);
    return this.http.get<PatientDetails[]>(`${this.endPoint_getPatientsByPhone}`);
  }


}

下面是错误屏幕图片

提前致谢

【问题讨论】:

标签: angular spring-boot spring-mvc spring-security spring-data-jpa


【解决方案1】:

解决此问题的一种方法是为您的本地开发设置代理。为此,请在您的根目录中创建一个“proxy.conf.json”。

{
  "/patient": {
    "target": "http://localhost:9001",
    "secure": false
  }
}

使用以下命令启动您的应用程序:“ng serve --proxy-config proxy.conf.json”。

如需完整示例,请查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2019-07-25
    • 2019-08-31
    • 2020-10-19
    • 2020-07-13
    相关资源
    最近更新 更多