jeudi 26 septembre 2019

How to fix method not allowed exception which i am getting on my PUT Request from angular 7 to laravel api

While doing a PUT request from angular 7 to laravel 5.8 api, i am getting a method not allowed exception when i check the network. It does the update but it shows the error also.

The application can be accessed by below link. While editing and updating the manufacturer data i.e name i get the error when i check the network

https://mincar-inventory.herokuapp.com/

Manufacturer TS file code

updateManufacturer(id: any, singleManufacturer: any){    this.carManufacturerService.updateManufacturer(id,singleManufacturer).subscribe(
       () => {
        this.toastr.success('Manufacturer Updated Successfully', 'Success', {timeOut: 5000});
        this.listAllManufacturers();
        this.updateManufacturerForm.reset();
        this.spinnerService.hide();
    });
  }

Manufacturer service TS file code

updateManufacturer(id: any, singleManufacturer: any): Observable<any>{
    return this.http.put<any>(this.url + '/' + id, singleManufacturer).pipe(
      retry(1),
      catchError(this.handleError)
    );
  }

Laravel Routes File code

Route::group(['prefix'=>'v1','middleware' => 'cors'],function(){
    Route::apiResource('/manufacturer', 'Api\v1\ManufacturerController')
    ->only(['index','show','destroy','edit','update','store']);
    Route::apiResource('/car-model', 'Api\v1\CarModelController')
    ->only(['index','show','destroy','edit','update','store']);
    Route::apiResource('/inventory', 'Api\v1\InventoryController');
});

Manufacturer controller update function

 public function update(Request $request, $id)
    {
        $manufacturer = Manufacturer::findOrFail( $id );
        $manufacturer->save($request->all());
        return Response()->json(["status"=>"success","message"=>"Manufacturer name updated successfully"]);
    }

CORS code

public function handle($request, Closure $next)
    {
      header("Access-Control-Allow-Origin: *");
      // ALLOW OPTIONS METHOD
      $headers = [
          'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
          'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
      ];
      if($request->getMethod() == "OPTIONS") {
          // The client-side application can set only headers allowed in Access-Control-Allow-Headers
          return Response::make('OK', 200, $headers);
      }
      $response = $next($request);
      foreach($headers as $key => $value)
          $response->header($key, $value);
      return $response;
    }

Getting unexpected MethodNotAllowedHttpException as we can see in the image link provided below

https://imgur.com/lSGjZqG



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire