Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

); } } export default TableRow;

Cấu trúc lại Router

  • Nội dung file index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './index.css';
import bootstrap from 'bootstrap';
import './bootstrap.min.css';
import DisplayItem from './components/DisplayItem';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
    
      
        
          
        
    ,
    document.getElementById('root'));
registerServiceWorker();
  • Kết quả màn hình khi truy cập vào http://localhost:3000/

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Form tạo item

API tạo item

API thêm item mới vào danh sách todo list như sau:

  • Url: http://localhost:3001/api/todos
  • Method: post
  • Parameters: title(string)

Kết quả khi chạy api:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Tạo form và call api

Tạo form add item

  • Tạo file src/components/CreateItem.js có nội dung như sau:
import React, {Component} from 'react';

class CreateItem extends Component {
    render() {
      return (
      

Create An Item


) } } export default CreateItem;
  • Sửa lại Router trong file src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './index.css';
import bootstrap from 'bootstrap';
import './bootstrap.min.css';
import DisplayItem from './components/DisplayItem';
import CreateItem from './components/CreateItem';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
    
      
        
          
          
        
    ,
    document.getElementById('root'));
registerServiceWorker();
  • Sửa file src/components/DiplayItem.js để thêm link đến form add item Thêm dòng
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

Và sửa dòng

thành dòng

Tạo xử lý form để post data

File src/components/CreateItem.js sẽ được thêm các lệnh xử lý form như sau:

import React, {Component} from 'react';
import axios from 'axios';
import { Redirect, Link } from 'react-router-dom';

class CreateItem extends Component {
  constructor(props){
    super(props);
    this.state = {
      title: ''
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(e){
    this.setState({
      title: e.target.value
    })
  }
  render() {
    return (
      

Create An Item


  Back Todo list
) } } export default CreateItem;

Chúng ta có giao diện form như sau:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Thêm function để call api

Trong file src/components/CreateItem.js sẽ thêm fucntion call api sau:

handleSubmit(e){
    e.preventDefault();
    const items = {
      title: this.state.title
    }
    let uri = 'http://localhost:3001/api/todos';
    axios.post(uri, items).then((response) => {
        return 
    });
  }

Sử dụng api ta sẽ có kết quả như sau:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs
Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Form edit & delete item

Tương tự với cách hoạt động của form tạo item chúng ta sẽ chỉnh sửa và thêm các file sau:

Form edit

Thêm file src/components/EditItem.js có nội dung như sau:

import React, {Component} from 'react';
import axios from 'axios';
import { Link, Redirect } from 'react-router-dom';

class EditItem extends Component {
  constructor(props) {
      super(props);
      this.state = {title: '', redirect: false};
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount(){
    axios.get("http://localhost:3001/api/todos/"+this.props.match.params.id)
    .then(response => {
      console.log(response);
      this.setState({ title: response.data.title });
    })
    .catch(function (error) {
      console.log(error);
    })
  }
  handleChange(e){
    this.setState({
      title: e.target.value
    })
  }

  handleSubmit(event) {
    event.preventDefault();
    const items = {
      title: this.state.title
    }
    let uri = 'http://localhost:3001/api/todos/'+this.props.match.params.id;
    axios.put(uri, items).then((response) => {
      this.setState({
        redirect: true
      })
    });
  }
  render() {
    if (this.state.redirect) {
      return ;
    }
    return (
      

Update Todo

Return to Todo list
) } } export default EditItem;

Tạo route để phần edit này có thể nhìn thấy trên giao diện, thêm các dòng code sau vào src/index.js:

import EditItem from './components/EditItem';


Xử lý delete

Để cập nhật xử lý cho phần Delete item, File src/components/TableRow.js sẽ được sửa như sau:

import React, { Component } from 'react';
import axios from 'axios';
import { Link, Redirect } from 'react-router-dom';

class TableRow extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    let uri = `http://localhost:3001/api/todos/${this.props.obj.id}`;
    axios.delete(uri);
      this.setState({
        redirect: true
      })
    }
  render() {
    if (this.state.redirect) {
      return ;
    }
    return (
        
); } } export default TableRow;

Trên giao diện sẽ hiển thị như sau:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Click vào button Edit sẽ hiển thị ra form sau:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Sau khi nhập dữ liệu để sửa ta click vào button Update dữ liệu sẽ được cập nhật vào DB.

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Khi click vào button xóa thì tương tự dữ liệu cũng sẽ được xóa khỏi DB.

Tham khảo

  • Reactjs.org
  • Axios
  • FrontEnd Github code
  • Nodejs API Github code

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Đã đăng vào thg 5 2, 2018 12:26 CH 1 phút đọc

Bài này sẽ nói về cách build một ứng dụng sử dụng ReactJs với phần server sử dụng API build bằng Nodejs.

Phần build server API Nodejs các bạn xem chi tiết tại bài sau Hướng dẫn xây dựng API đơn giản với Nodejs và Mysql

Khởi tạo project

Requirement

  • Nodejs 6.x
  • Mysql 5.x
  • ReactJs 16.x

Create react app

npm install -g create-react-app
create-react-app my-app

Kết quả file package.json sẽ như sau:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-scripts": "1.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Để chạy ta dùng lệnh:

cd my-app
npm start

Running Test

Truy cập app trên trình duyệt với đường link như bên dưới:

http://localhost:3000/

Giao diện chúng ta nhìn thấy sẽ như sau:

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Cách gọi API từ ReactJs

Cài đặt Axios để gọi API

Chạy lệnh sau

npm install axios ---save

API Nodejs mình đã nói từ bài trước các bác lấy code về chạy nhé. Lấy code tại nodejs_api

Và fix port để chạy api này là 3001 chẳng hạn.

Danh sách items

Kết quả từ API trả về như sau:

URL: http://localhost:3001/api/todos

Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Trên frontend ta sẽ gọi bằng cách.

  • File src/App.js mặc định sẽ là:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      
Hướng dẫn xây dựng api đơn giản với nodejs và mysql kết hợp frontend dùng reactjs

Như vậy ta đã gọi một api cơ bản với việc sử dụng react

Tham khảo

  • Reactjs.org
  • Axios
  • Github code

All rights reserved

Bài này sẽ nói về cách build một ứng dụng sử dụng ReactJs với phần server sử dụng API build bằng Nodejs. Và nói tiếp cách tạo form: thêm, sửa, xóa dữ liệu bằng API Nodejs, sử dụng ReactJs.

Phần build server API Nodejs các bạn xem chi tiết tại bài sau Hướng dẫn xây dựng API đơn giản với Nodejs và Mysql Phần trước của bài này bạn xem ở đây Hướng dẫn xây dựng API đơn giản với Nodejs và Mysql, kết hợp frontend dùng reactjs

Như vậy chúng ta đã gọi một api cơ bản với việc sử dụng Reactjs.

Cấu trúc lại code ReactJs

Trong bài trước về cơ bản cách tổ chức code rất nguyên thủy, mình sẽ cấu trúc lại code FrontEnd Github code hiện tại thành các components như sau:

Component hiển thị danh sách

Tạo component DisplayItem

Danh sách Todo list hiển thị ban đầu tại file App.js, mình sẽ đổi tên thành component DisplayItem src/components/DisplayItem.js

Nội dung của file src/components/DisplayItem.js là:

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';
import { Link } from 'react-router-dom';

class DisplayItem extends Component {
  constructor(){
    super();
    this.state ={items: []};
   }
  componentDidMount() {
    axios.get('http://localhost:3001/api/todos')
     .then(response => {
      console.log(response.data);
       this.setState({ items: response.data });
     })
     .catch(function (error) {
       console.log(error);
     })
    }
    tabRow() {
      if (this.state.items instanceof Array) {
        return this.state.items.map(function(object, i) {
          return ;
        })
      }
    }
    render() {
      return (
          

Todo List

{this.tabRow()}
Add item
ID Title Actions
); } } export default DisplayItem;

Tạo component TableRow

Trong file src/components/DisplayItem.js chúng ta thấy có một component TableRow được import vào. Mục đích của component TableRow là để hiển thì từng dòng trong danh sách Todo.

Nội dung của component src/components/TableRow.js như sau:

import React, { Component } from 'react';

class TableRow extends Component {
  render() {
    return (
        
{this.props.obj.id} {this.props.obj.title}  
Add item Add item
{this.props.obj.id} {this.props.obj.title} Edit