0

I'm trying to create a web application using Angular and Node for study, but my PUT request isn't working even though my GET requests work. It seems like Node is ignoring the requests and I can't find why. In my app I try to edit the name of a user when clicking a button and I can see that the request works until it gets to the http client in users-service.service.ts.

users.component.html

<router-outlet></router-outlet>
<h3>Usuários</h3>

<table>
<tr><td>Nome</td></tr>
<tr *ngFor="let user of users"><td>{{user.first_name}}</td><td><button    (click)="showUserInfo($event, user)">Editar</button></td></tr>
</table>

<br/><br/>
<div>
<label>First Name: </label><input type="text" value="{{user.first_name}}" (input)="user.first_name = $event.target.value">
<label>Last Name: </label><input type="text" value="{{user.last_name}}" (input)="user.last_name= $event.target.value">
<button (click)="updateUser()">Salvar</button>
</div>

<br/><br/>
<button (click)="loadAllUsers()">Reload</button>

users.component.ts

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { UsersService, User } from './../users-service.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-users',
  providers: [UsersService, HttpClient, HttpClientModule],
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.sass']
})
export class UsersComponent implements OnInit {

 private users: User[];
 private user: User = {first_name: '', last_name: '', id: null};

  constructor(private service: UsersService) {
    this.loadAllUsers();
  }

  ngOnInit() {}

  showUserInfo(event, u : User) {
    this.user = u;
  }

  loadAllUsers() {
    this.service.getAllUsers().subscribe(valor => { this.users = valor as User[] });
   } 

  updateUser() {
    console.log(this.user);
    this.service.updateUser(this.user);
  }
}

users-service.service.ts

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

import { Observable } from 'rxjs';


export interface User{
    first_name: string,
    last_name: string,
    id: number
}

@Injectable()
export class UsersService{

  constructor(private http: HttpClient) { }

  getAllUsers(): Observable<User[]>{
    return this.http.get<User[]>("http://localhost:4600/api/users");
  }

  updateUser(user: User): Observable<void>{
    console.log('Updating: ' + user);
    console.log("http://localhost:4600/api/users/" + user.id);
    return this.http.put<void>("http://localhost:4600/api/users/" + user.id, user);
  }
}

server.js

const express = require('express');
app = new express();
const morgan = require('morgan');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(morgan('dev'));
app.use('*', cors());

app.listen(4600, () => {
     console.log("Server listening on port 4600...");
});

//All users
app.get("/api/users", (req, res) => {
    let connection = getConnection();

    connection.query('SELECT * FROM USERS', (err, result) => {
        if(err){
            throw err;
        }
        console.log(result);
        res.json(result);
    });
});

//Specific user
app.get('/api/users/:id', (req, res) => {
    getConnection().query('SELECT * FROM USERS WHERE ID = ?', req.params.id, (err, result) => {
        if(err){
            console.log(err.message);
            throw err;
        }
        res.json(result);
    });
});

//Update user
app.put("/api/users/:id", (req, res) => {
    console.log('PUT request received...');
    getConnection().query("UPDATE USERS SET FIRST_NAME = ?, LAST_NAME = ? WHERE ID = ?", [req.body.first_name, req.body.last_name, req.body.id],     (err, result) => {
        if(err){
            console.log(err.message);
            throw err;
        }
        res.send(201, req.body); 
    });
});

//Delete user
app.delete('/api/users/:id', (req, res) => {



});

function getConnection(){
    return mysql.createConnection({
        host: 'localhost',
        user: '',
        password: '',
        database: 'test'
    }); 
}

EDIT 1

Based on @tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by @KeaganFouche in the question bellow helped me: Angular 4.0 http put request

New update method in the Angular service:

updateUser(user: User): void{
    console.log('Updating: ' + user);
    console.log("http://localhost:4600/api/users/" + user.id);
     this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}
  • You only have `get` and `post` actions defined, not `put`. Should that be `app.put("/api/users/:id", ...)`? – tadman Jan 28 '19 at 21:50
  • I was testing to see if POST would work, but it didn't either. I forgot to change it back to PUT. By not working I mean the message "PUT request received..." isn't displayed after I press the button. – Jean Willian S. J. Jan 28 '19 at 21:54
  • 1
    As always, check that you're making the correct request from your front-end application using your browser's "Network" debugger. You may also want to stub in an Express handler that logs all requests so you can see what's going on if you don't have that yet. – tadman Jan 28 '19 at 21:58
  • Possible duplicate of [Using the PUT method with Express.js](https://stackoverflow.com/questions/18601922/using-the-put-method-with-express-js) – Alvaro Silvino Jan 28 '19 at 22:33

1 Answers1

0

Based on @tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by @KeaganFouche in the question bellow helped me: Angular 4.0 http put request

New update method in the Angular service:

updateUser(user: User): void{
    console.log('Updating: ' + user);
    console.log("http://localhost:4600/api/users/" + user.id);
     this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}