CORS policy preflight 403 error at sending request from Angular web server to GO backend server

133 views Asked by At

I am trying to send a http request from a frontend app created with Angular, but even though I tried to set the allowed access control allow origin header on both servers (fe/be) I still receive this error: "Access to XMLHttpRequest at 'http://localhost:3000/rcVolume' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. "

This is my main func:

func main() {

    store, err := NewPostgresStore()
    if err != nil {
        log.Fatal(err)
    }

    if err := store.Init(); err != nil {
        log.Fatal(err)
    }

    server := NewAPIServer(":3000", store)
    server.Run()

}

This is my server configuration in go:

func (s *APIServer) Run() {

    router := mux.NewRouter()

    router.HandleFunc("/rcVolume", makeHTTPHandleFunc(s.handleRcVolume))

    log.Println("JSON API Server running on port: ", s.listenAddr)

    headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"})
    origins := handlers.AllowedOrigins([]string{"*"})
    methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"})

    http.ListenAndServe(s.listenAddr, handlers.CORS(headers, origins, methods)(router))
}

This is the implementation of the handle methods:

func (s *APIServer) handleRcVolume(w http.ResponseWriter, r *http.Request) error {
    if r.Method == "GET" {
        return s.handleGetRcVolumes(w, r)
    }
    if r.Method == "POST" {
        return s.handleCreateRcVolume(w, r)
    }

    return fmt.Errorf("method not allowed %s", r.Method)
}

Respectively:

func (s *APIServer) handleGetRcVolumes(w http.ResponseWriter, r *http.Request) error {
    
    rcVolumes, err := s.store.GetRcVolumes()
    if err != nil {
        return err
    }
    
    return writeJSON(w, http.StatusOK, rcVolumes)

}

writeJSON method:

func writeJSON(w http.ResponseWriter, status int, v any) error {
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
    w.WriteHeader(status)

    return json.NewEncoder(w).Encode(v)
}

Angular header configuration:

export const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'DELETE, POST, GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With'
  })
};

and:

@Injectable({
    providedIn: 'root'
})
export class RcVolumesServiceApi {
  private url = 'http://localhost:3000'

  constructor(private httpClient: HttpClient) { }

  getRcVolumes() {
    return this.httpClient.get<any[]>('http://localhost:3000/rcVolume', httpOptions)
  }
}

and:

@Injectable({
  providedIn: 'root'
})
export class RcVolumeService {
  
  datePipe = new DatePipe('en_US', 'UTC');
  
  constructor(private api: RcVolumesServiceApi) {}

  public get rcVolumes() {
    return this.api.getRcVolumes().pipe(
      map((rcVolumes) => {
        return rcVolumes;
      })
    )
  }
}

component.ts:

export class RcVolumeComponent implements OnInit {

  displayedColumns: string[] = ['debtor_no', 'volume'];
  dataSource = ELEMENT_DATA;
  rcVolumes: RcVolumePO[]

  constructor(private rcVolumeService: RcVolumeService ) { }

  ngOnInit(): void {}

  initializeValue() {
    this.rcVolumeService.rcVolumes.subscribe(
      (res: any) => {
        this.rcVolumes = res
      }
    )
    console.log(this.rcVolumes)
  }
}

Does anyone know where should I place the header to allow all origins so that I can get rid of the error? Or maybe I am missing something else, plase help!

0

There are 0 answers