I get 404 code at a PUT but GET works normally: {body: {...}, url: "api/modes/1", headers: Httpheaders, status: 404, statusText: "Not Found"}

Asked

Viewed 101 times

0

I am a student and beginner in Angular and at the moment I will continue to use PTO in a project, but before that I am preparing CRUD methods so I can work on them, so I am going through request problems and do not understand what I am doing wrong, when I do a GET using the Url api/modes or api/modes/1 the request is successful, but when trying to make a PUT using the address api/modes/1 and returned me a mistake 404:

{body: {...}, url: "api/modes/1", headers: Httpheaders, status: 404, statusText: "Not Found"}

I’m using:

  • Angular 9.1.8
  • Angular in-memory-web-api 0.11.0

#mode.service.ts

import { HttpHeaders, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from "@angular/core";

import { Observable, of } from 'rxjs';

import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { Mode } from "./mode.model";

@Injectable()

export class ModeService {
  public modeUrl = "api/modes";

  public constructor(private http: HttpClient) {}

  public getModes(): Observable<Mode[]> {

    return this.http.get<Mode[]>(this.modeUrl)
      .pipe(
        catchError(this.handleErrors)
      )

  }
  
  public getMode(id: number): Observable<Mode> {
    let url = `${this.modeUrl}/${id}`;

    return this.http.get<Mode>(url)
      .pipe(
        catchError(this.handleErrors)
      )
  }

  public updateMode(mode: Mode): Observable<Mode> {
    let url = `${this.modeUrl}/${mode.id}`;
    let body = JSON.stringify(mode);
    let headers = new HttpHeaders({'Content-type': 'application/json'});
    
    return this.http.put<Mode>(url, body, {headers: headers} )
      .pipe(
        catchError(this.handleErrors)
      )

  }

  private handleErrors(error: HttpErrorResponse) {
    console.log("SALVANDO O ERRO NUM ARQUIVO DE LOG - DETALHES DO ERRO => ", error);
    return throwError(error);
  }

}

#mode-Detail.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

// import "rxjs/add/operator/switchMap";
import { switchMap } from 'rxjs/operators';

import { Mode } from '../shared/mode.model';
import { ModeService } from '../shared/mode.service';

@Component({
  selector: 'mode-detail',
  templateUrl: './mode-detail.component.html'
})

export class ModeDetailComponent implements OnInit {
  public mode: Mode;

  public constructor (
    private modeService: ModeService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  public ngOnInit() {
    this.route.params.pipe(switchMap(
        (params: Params) => this.modeService.getMode(+params['id'])))
      .subscribe(
        mode => this.mode = mode,
        error => alert("Ocorreu um erro no servidor, tente mais tarde.")
      );
  }

  public updateMode() {
    if (!this.mode.name) {
      alert("O módulo deve ter um nome")
    } else {
      this.modeService.updateMode(this.mode)
        .subscribe(
          () => alert("Módulo atualizado com sucesso!"),
          () => alert("Ocorreu um erro no servidor, tente mais tarde.")
        )
    }
  }  

  public goBack() {
    this.location.back();
  }
}

#mode-Detail.component.html

<h1 class="page-header font-weight-black text-secondary">Módulo {{ mode?.name }}</h1>
<br>
<div class="container-fluid bg-light shadow rounded ">

  <br>
  <div class="form-row" *ngIf="mode">
    <div class="form-group col-lg-12">
      <label for="name" class="col-sm-2 control-label text-body">Nome</label>
      <div class="col-sm-12">
        <input [(ngModel)]="mode.name" type="text" class="form-control text-muted" placeholder="Nome">
      </div>
    </div>
    <div class="form-group col-lg-12">
      <div class="col-sm-12 text-right">
        <button class="btn btn-default text-secondary" (click)="goBack()">Voltar</button>
        <button type="submit" class="btn btn-primary btn-medium text-light" (click)="updateMode()">Salvar</button>
      </div>
    </div>

  </div>
  <br>

</div>

Error Console

inserir a descrição da imagem aqui

1 answer

0


Updating:

I uninstalled the package angular in memory api, this lib was used to intercept HTTP requests and simulate responses, but unfortunately using it in this project Angular 9 did not work in any way that I tried, unlike another project that I develop in Angular 4 which works perfectly on it.

After uninstalling the package above, I switched to the package json-server, it will do the same job in responding to HTTP requests, I found it a little simpler than the other but for my case to use in CRUD came to work very well!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.