Rest API CRUD – Node.js + express + React.js + MySQL Part 4: List

Node.js (Backend)

Route

src/routes/EmployeeRoute.js

router.get('/list', EmployeeController.list);

Controller

controllers.list = async (req, res) => {

  const data = await Employee.findAll({
    include: [ Role ]
  })
  .then(function(data){
    return data;
  })
  .catch(error => {
    return error;
  }); 

  res.json({success : true, data : data});

}

CORS

src/App.js

// Access-Control-Allow-Origin: Para controlar quien puede consumir mi API
// Access-Control-Allow-Headers: Para configurar los headers que acepta la API
// Access-Control-Allow-Methods: Para declarar los métodos que acepta el API

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

React.js ( Frontend )

src/module/list.js

Install axios

npm install axios

Import axios

import axios from 'axios';

State

  constructor(props){
      super(props);
      this.state = {
        listEmployee:[]
      }
    }

componentDidMount

componentDidMount(){

      axios.get("http://192.168.1.6:3000/employee/list")
      .then(res => {
        const data = res.data.data;
        this.setState({ listEmployee:data });
      })
      .catch(error => {
        alert(error)
      });

    }

Render

{this.loadFillData()}

Function for loadFillData

loadFillData(){

    return this.state.listEmployee.map((data)=>{
      return(
        <tr>
          <th>{data.id}</th>
          <td>{data.role.role}</td>
          <td>{data.name}</td>
          <td>{data.email}</td>
          <td>{data.address}</td>
          <td>{data.phone}</td>
          <td>
            <button class="btn btn-outline-info "> Edit </button>
          </td>
          <td>
            <button class="btn btn-outline-danger "> Delete </button>
          </td>
        </tr>
      )
    });
  }

Añadir un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *