1

I am trying to perform the update function of a model, trying to call the Update method in the API via PUT.

This is my service client:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, RequestMethod, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';

[...]

    updateClients(client_id, data){
        let headers = new Headers({ 'Content-Type': 'application/json' });

              let body = JSON.stringify(data);

              return this.http.put(`${this.baseUrl}/client/`+client_id, body, headers)
                .toPromise()
                .then(response => response.json().data)
                .then(items => items.map((item, idx)  => {
                  return{
                    id: item.id
                  };
                }));
    }

But it does not work since the method goes by OPTIONS and not PUT. And in my browser console it comes out: XMLHttpRequest can not loadhttp://ip/api/client/5. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

But, in the API (Laravel 5.3) the PUT method is enabled. I have tried it with POSTMAN and it's works. And in my response headers:

Access-Control-Allow-Origin: *
Allow: GET, HEAD, PUT, PATCH, DELETE
Cache-Control: no-cache
Connection: keep-alive

Why does it come via options request and not put? The POST method works in angular 2.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

1 Answers1

2

OPTIONS is a preflight request automatically sent by the browser in some CORS situations. If the server doesn't respond with the expected CORS headers (Access-Control-Allow-Origin and others) the browser won't make the PUT request at all.

You need to configure the server to respond with the expected headers to be able to use this server directly from Angular (or JS in general)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567