5

I have an rest api which i could use post and get requests. But when i want to use put and delete request it returns error 403. But also when i try to put and delete with Postman app (an app for json requests) all is works well. Im really confused. Let me prove the problem with some screenshots. (Im censored links for security, sorry for that)


Chrome console; enter image description here Postman App; enter image description here


Any my put code;

  /** PUT: update the firm on the server */
updateFirm (firm: Firm): Observable<any> {
 console.log(firm);

 return this.http.put(this.firmUrl+"put/"+String(firm.id), firm, httpOptions).pipe(
   tap(_ => console.log(`updated firm id=${firm.id}`)),
   catchError(this.handleError<any>('updateFirm'))
 );
}

I will be very appreciated if you could help me. Have nice day

Cem Kocagöz
  • 634
  • 12
  • 26

4 Answers4

2

I had a similar situation and found out that Angular 2 performs a OPTIONS method before a POST is done! OPTIONS was missing in "Access-Control-Allow-Methods".

If I check your log, then I think that you should also allow OPTIONS: With angular, and perl as a backend, I had to allow the following:

-"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS',

Rob Lassche
  • 841
  • 10
  • 16
2

Proxy solves your problem. A nice and fast solution could be to borrow one (like https://cors-anywhere.herokuapp.com) to test then do your own. Here is an example :

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-analyzer',
  templateUrl: './analyzer.component.html',
  styleUrls: ['./analyzer.component.scss']
})
export class AnalyzerComponent implements OnInit {

  res;

  constructor(private http: HttpClient) {
    this.getDeck().subscribe(res => {console.log(res); this.res = res; });
  }

  ngOnInit() {
  }

  getDeck() {
    const headers = new HttpHeaders({
      'X-Requested-With': 'XMLHttpRequest'
    });
    return this.http.get('https://cors-anywhere.herokuapp.com/https://www.keyforgegame.com/api/decks/30763530-041c-4e15-b506-3456e79141d2/',
      {headers: headers}
      );
  }

}

enter image description here

Leasye
  • 261
  • 1
  • 8
  • 19
1

It looks like a CORS error, you are doing the http request from your local machine on localhost to the backend on a different URL. The only way to solve this would be to allow requests from different origins on the backend. Or possibly to run the backend on your local machine.

End
  • 591
  • 3
  • 10
1

Your problem is about CORS for HTTP OPTIONS request.

Indeed, before the execution of the HTTP PUT request, your client has to make a OPTIONS request, in order to add your httpOptions variable, which contains your header.

So you have to authorize the execution of OPTIONS request in the code of your server.

veben
  • 19,637
  • 14
  • 60
  • 80