+4

[NodeJs][React] Học cách làm app bằng NodeJs với React (Phần 1)

Trong thời đại công nghệ 4 đang phát triển như ngày nay, rõ ràng việc áp dụng kỹ thuật không gian thực là 1 điều không thể thiếu. Trong seri bài học làm ứng dụng bằng NodeJs và ReactJs hôm nay, tôi sẽ đi cùng với các bạn làm 1 ứng dụng mà ta sử dụng các công nghệ realtime hiện nay bao gồm: NodeJs, Express JS, ReactJs, Mongo DB. Việc cài đặt NodeJs thì các bạn có thể tham khảo trên google hay ngay trên Viblo cũng có khá nhiều bài viết về cài đặt ban đầu nên mình bỏ qua.

Setup ban đầu

Đầu tiên bạn tạo 1 folder là blog. Sau đó gõ lệnh npm init sau đó có hướng dẫn làm theo, sau khi làm xong có kết quả và thêm luôn thư viện express. Ta có file packeage.json như sau:

{
  "name": "huynguyen_framgia_blog",
  "version": "1.0.0",
  "description": "Tutorial build app by nodejs express, react, mongo Db",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Huy Nguyen - Framgia Vietnam",
  "license": "ISC",
  "dependencies": {
    "express": "4.16.2"
  }
}

Để test thử xem node chạy bình thường không ta tạo 1 file view/index.html như sau

<body>
	Hello world
</body>

và viết file index.js

var express = require('express');
var path = require('path');

var app = express();
app.use(express.static(path.join(__dirname, '/view')));

app.listen(777, function() {
	console.log('started listen port', 777);
});

Và cuối cùng chạy node index.js rồi chuyển sang trình duyệt gõ localhost:777 và kết quả hiển ra page có chữ Hello world là coi như phần cài đặt xong.

Chức năng đăng nhập

Giao diện trang login

Ta tạo thêm 1 file signin.html trong folder view. Đầu tiên ta thêm giao diện bootstrap

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Sau đó thêm thư viện ReactJs 15

<script src="https://fb.me/react-15.1.0.js"></script>
<script src="https://fb.me/react-dom-15.1.0.js"></script>

Do ReactJs phiên bản 15 này sử dụng JSX để dựng view, và để chuyển đổi từ JSX sang giao diện web thì ta cần sử dụng thư viện babel

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Đồng thời thêm div để xác định vị trí chính khi load ReactJs

<div id="app" class="container">
</div>

Như vậy file view/signin.html sẽ như sau:

<html>
	<head>
		<title>Sign in</title>
		<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	</head>
    <body>
        <div id="app" class="container">
        </div>
        <script src="https://fb.me/react-15.1.0.js"></script>
        <script src="https://fb.me/react-dom-15.1.0.js"></script>
        <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
        <script type="text/jsx" src="signin.js"></script>
    </body>
</html>

File signin.js

Tiếp đến ta làm file xử lý giao diện bằng React. Đầu tiên ta tạo 1 file signin.js như sau

class Signin extends React.Component {
    render() {
        return (
            <form className="form-signin">
                <h2 className="form-signin-heading">Đăng nhập</h2>
                <label for="inputEmail" className="sr-only">Nhập địa chỉ email
                </label>
                <input type="email" id="inputEmail" className="form-control" placeholder="Email" required autofocus />
                <label for="inputPassword" className="sr-only">Mật khẩu</label>
                <input type="password" id="inputPassword" className="form-control" placeholder="Mật khẩu" required />
                <button className="btn btn-lg btn-primary btn-block" type="button">Đăng nhập
                </button>
            </form>
        );
    }
}
ReactDOM.render(<Signin / >, document.getElementById('app'));

Khi chạy đường link localhost:777/signin.html ta có kết quả như sau

Xử lý các sự kiện trên các input

Đầu tiên ta thêm các sự kiện vào các input như sự kiện thay đổi input email và password, cũng như khi click vào button signin

<input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email" required autofocus />
<input type="password" onChange={this.handlePaswordChange} id="inputPassword" className="form-control" placeholder="Mật khẩu" required />

Tiếp đến ta xử lý 2 sự kiện onChange vừa thêm vào trong file signin.js Sau đó ta khai báo 2 biến pros email và password

       constructor(props) {
            super(props);
            this.handleEmailChange = this.handleEmailChange.bind(this);
            this.handlePasswordChange = this.handlePasswordChange.bind(this);
            this.state = {
              email:'',
              password:''
            };
        }

Vậy giờ file signin.js sẽ như sau

class Signin extends React.Component {
    constructor(props) {
      super(props);
      this.signIn = this.signIn.bind(this);
      this.handleEmailChange = this.handleEmailChange.bind(this);
      this.handlePasswordChange = this.handlePasswordChange.bind(this);
      this.state = {
        email:'',
        password:''
      };
    }
    handleEmailChange(e){
      this.setState({email:e.target.value})
    }
    handlePasswordChange(e){
      this.setState({password:e.target.value})
    }
    signIn(){
        alert('Email address is ' + this.state.email + ' Password is ' + this.state.password);            
    }
    render() {
        return (
            <form className="form-signin">
                <h2 className="form-signin-heading">Đăng nhập</h2>
                <label for="inputEmail" className="sr-only">Nhập địa chỉ email
                </label>
                <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email" required autofocus />
                <label for="inputPassword" className="sr-only">Mật khẩu</label>
                <input type="password" onChange={this.handlePaswordChange} id="inputPassword" className="form-control" placeholder="Mật khẩu" required />
                <button className="btn btn-lg btn-primary btn-block" type="button" onClick={this.signIn}>Đăng nhập
                </button>
            </form>
        );
    }
}

ReactDOM.render(<Signin / >, document.getElementById('app'));

Gửi data từ ReactForm lên Node Server như sau

Ở đây để gửi data từ Form sinh ra từ React lên Node Server ta sử dụng Axios bằng cách thêm vào file signin.html như sau

axios.post('/signin', {
  email: this.state.email,
  password: this.state.password
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

Để nhận được data gửi lên thì ta sử dụng thư viện body-parser bằng lệnh sau npm install body-parser --save Sau đó trong file index.js ta bổ sung như sau để nhận được data

var bodyParser = require("body-parser");
app.use(bodyParser.json());

app.post('/signin', function (req, res) {
  var user_name=req.body.email;
  var password=req.body.password;
  if(user_name=='admin' && password=='admin'){
  	res.send('success');
  }
  else{
  	res.send('Failure');
  }
})

Chức năng đăng ký

Vì như ở trên ta làm màn hình đăng nhập, giờ làm màn hình đăng ký, nhưng vì vốn signin với signup là 2 khối khác nhau với đường dẫn khác nhau ta cần sử dụng đến React Router Ta thêm thư viện

<script src="https://npmcdn.com/react-router@3.0.2/umd/ReactRouter.min.js"></script>

Trong file sigin.js ta thêm phần khai bao Route:

var Router = window.ReactRouter.Router;
var Route = window.ReactRouter.Route;
var hashHistory = window.ReactRouter.hashHistory;
var Link = window.ReactRouter.Link;

Và rồi khai báo trong phần RenderDom

<Router history={hashHistory}>
        <Route component={Signin} path="/"></Route>
        <Route component={Signup} path="/signup"></Route>
    </Router>,

Tiếp đến ta tạo 1 comment phần signup như sau

class Signup extends React.Component{
  render() {
      return (
        <div>
          <form className="form-signin">
            <h2 className="form-signin-heading">Please sign up</h2>
            <label for="inputName" className="sr-only">Name</label>
            <input type="name" onChange={this.handleNameChange} id="inputName" className="form-control" placeholder="Name" required autofocus />
            <label for="inputEmail" className="sr-only">Email address</label>
            <input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required autofocus />
            <label for="inputPassword" className="sr-only">Password</label>
            <input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />
            
            <button className="btn btn-lg btn-primary btn-block" onClick={this.signUp} type="button">Sign up</button>
          </form>
          <div>
            <Link to="/">{'Signin'}</Link>
          </div>
        </div>    
      )
    }
}

Kết luận

Qua phần 1 ta học được cách tạo 2 view signin và signup cũng như tạo route để cho 2 link tương đương. Tiếp đến ta hiểu cách truyền dữ liệu từ ReactJs lên Node Server như thế nào. Bài tiếp theo ta sẽ làm đến phần tạo user trong DB và đăng nhập nữa.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí