+1

Kết nối React Frontend với Node.js Express Backend

Trong ví dụ này, bạn sẽ học cách thiết lập giao tiếp giữa frontend dựa trên React và backend Node.js bằng Express. Hãy cùng tìm hiểu nhé!

Thiết lập dự án

Đầu tiên, hãy tạo một thư mục có tên simple_project theo vị trí bạn muốn và mở thư mục đó trong IDE yêu thích của bạn.

Bây giờ, chúng ta hãy tạo cấu trúc dự án. Nó sẽ đơn giản như thế này:

  • Thư mục frontend (ứng dụng React)
  • Thư mục backend (Node.js API)

Thiết lập giao diện

Bên trong thư mục frontend, chúng ta sẽ sử dụng Vite để tạo ứng dụng React cùng với Tailwind CSS. Điều hướng vào thư mục trước khi chạy lệnh:

npm create vite@latest
Project name: .
Select a framework: React
Select a variant: JavaScript

Bây giờ, hãy cài đặt các phần phụ thuộc:

npm install

Tiếp theo, cài đặt Tailwind CSS:

npm install tailwindcss @tailwindcss/vite

Thư mục frontend của bạn bây giờ sẽ có cấu trúc như sau:

node_modules
public
src
  ├── App.jsx
  ├── index.css
  ├── main.jsx
.gitignore
...

Cấu hình Vite

Sửa đổi vite.config.js để bao gồm Tailwind CSS:

import { defineConfig } from 'vite';
import tailwindcss from "@tailwindcss/vite";
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react(), tailwindcss()]
});

Tạo thành phần ứng dụng

Biên tập App.jsx:

function App() {
  return (
    <div className="min-h-screen w-full bg-gray-100 flex items-center justify-center flex-col gap-10">
      <h1 className="text-5xl font-bold text-gray-800">
        Backend with Express and Node
      </h1>
      <ul className="rounded-2xl shadow-lg bg-white space-y-3"></ul>
    </div>
  );
}

export default App;

Thiết lập phần cuối

Để tạo phần phụ trợ, hãy điều hướng đến thư mục backend:

cd backend

Khởi tạo một tập tin package.json:

npm init -y

Sửa đổi package.json để đặt main thành server.js và thêm nội dung sau:

"type": "module"

Bây giờ, hãy cài đặt Express và CORS:

npm install express cors

Tạo một tệp có tên server.js bên trong thư mục backend và thêm nội dung sau:

import express from "express";
import cors from "cors";

const app = express();

const CORS_OPTIONS = {
  origin: ["http://localhost:5173"]
};

app.use(cors(CORS_OPTIONS));

app.get("/", (req, res) => {
  res.json({
    blogPosts: [
      {
        title: "\"Neymar's Return to Santos and Its Impact on Grêmio\","
        content: "Grêmio will face tougher competition now that Neymar is back at Santos."
      },
      {
        title: "\"The Importance of Digital Marketing for Your Business\","
        content: "Digital marketing is a powerful tool to boost your business growth."
      }
    ]
  });
});

app.listen(8080, () => {
  console.log("Server is running on port 8080");
});

Vì giao diện người dùng và giao diện quản trị chạy trên các cổng khác nhau ( 5173 và 8080 ), chúng ta sử dụng CORS để cho phép giao tiếp giữa chúng.

Lấy dữ liệu từ Frontend

Để lấy bài đăng trên blog từ phần phụ trợ, hãy quay lại thư mục frontend và cài đặt axios :

npm install axios

Cập nhật App.jsx:

import axios from "axios";
import { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);

  const fetchData = async () => {
    const response = await axios.get("http://localhost:8080");
    setData(response.data.blogPosts);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="min-h-screen w-full bg-gray-950 flex items-center justify-center flex-col gap-10">
      <h1 className="text-5xl font-bold text-gray-100">
        Backend with Express and <span className="text-green-400"> Node</span>
      </h1>
      <ul className="rounded-2xl shadow-lg p-5 bg-white space-y-3">
        {data.map((post, index) => (
          <li key={index} className="bg-sky-100 p-4 rounded-2xl hover:scale-105 transition-transform">
            <p className="text-xl font-semibold text-gray-800">{post.title}</p>
            <p className="text-sm text-gray-600">{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Hook useState lưu trữ dữ liệu đã lấy và useEffect đảm bảo dữ liệu được truy xuất khi thành phần được gắn kết.

Chạy ứng dụng

Khởi động cả frontend và backend cùng lúc. Mở hai cửa sổ terminal và chạy:

# In the frontend folder
npm run dev

# In the backend folder
node server.js

Bây giờ, hãy mở http://localhost:5173/ trên trình duyệt của bạn. Bạn sẽ thấy các bài đăng trên blog được hiển thị trên màn hình.

Xin chúc mừng! Bạn đã kết nối thành công giao diện React với giao diện Node.js bằng Express.


All rights reserved

Bình luận

Đăng nhập để bình luận
Avatar
+1
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í