1

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')
  }) 

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

But I tested in the update method with Postman, it works fine, also in my server, express, I have enabled all of these: res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true);
Yes, but with Postman, you are in a Chrome plugin so you can have fewer restrictions. That's great for the CORS headers on the server side. But it's not enough regarding CORS preflight requests. You should use the cors module in your express application: github.com/expressjs/cors#enabling-cors-pre-flight (globally or per request).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.