Vicheanak
Vicheanak

Reputation: 6684

Angular2 Http PUT gives wrong RequestMethod

I can't understand why I can't use http put in Angular2.

When I'm doing http post, it give the correct request method:

enter image description here

However, when I use http put: it give OPTIONS as the request method:

enter image description here

I meant what the heck is this?

Here is the method that I'm using for post:

  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  let options = new RequestOptions({ headers: headers });
  var body = 'amount=' + 12;
  this.http.post(this.host + '/orders', body, options)
  .map(res => res.json())
  .subscribe(data => {
    resolve('success')
  });

Here is the method that I'm using for PUT.

  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  let options = new RequestOptions({ headers: headers });
  let body = 'amount=' + 12;
  this.http.put(this.host + '/orders/1', body, options)
  .map(res => res.json())
  .subscribe(data => {
    resolve('success')
  }) 

Upvotes: 1

Views: 657

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202216

I think that it's because of CORS. It's not related to Angular2. In the case of your POST method, a simple method will be executed. In the case of PUT, you're in the case of a preflight one so an additional request (an OPTIONS one) will be involved under the hood by the browser. And it seems that you have 404 on this OPTIONS method.

As a reminder:

Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.

Preflighted requests. When the "simple requests" use case doesn’t apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

I think that these articles could interest you:

Upvotes: 1

Related Questions