Axios lấy dữ liệu từ mongodb
Ghi chú của biên tập viên. Hướng dẫn ngăn xếp MERN này được cập nhật lần cuối vào ngày 2 tháng 12 năm 2022 để mở rộng và cập nhật phần giao diện người dùng của hướng dẫn. Bản cập nhật này bao gồm các phần Axios, React Hook và ủy quyền mới Show
Hướng dẫn này là tất cả về ngăn xếp MERN. Chúng tôi sẽ phác thảo những điều cơ bản về ngăn xếp MERN và trình bày cách sử dụng nó bằng cách phát triển một ứng dụng CRUD đơn giản từ đầu Để hiển thị cách ngăn xếp MERN hoạt động, trước tiên chúng tôi sẽ định cấu hình phía máy chủ bằng cách kết nối Nút. js và Express. js sang MongoDB trên phần phụ trợ. Sau đó, chúng tôi sẽ tạo một số API. Sau đó, chúng tôi sẽ hướng dẫn bạn xây dựng giao diện người dùng, sử dụng React để xây dựng giao diện người dùng của chúng tôi. Khi cả hai hoàn tất, chúng tôi sẽ kết nối giao diện người dùng với phần phụ trợ Nhảy ra đằng trước Ngăn xếp MERN là gì?Cụm từ MERN stack bao gồm các công nghệ sau cho phép phát triển ứng dụng nhanh hơn
MongoDB, Express. js và Nút. js giúp bạn xây dựng phần phụ trợ của ứng dụng, trong khi React cung cấp năng lượng cho phần đầu. Nút. js và React được xếp hạng là hai công nghệ và khung web phổ biến nhất, theo báo cáo gần đây nhất. Và MongoDB cũng là một trong những thứ dành cho nhà phát triển. Khoảng 16.535.063 trang web sử dụng React để tăng sức mạnh cho giao diện người dùng của họ. Bạn có thể dễ dàng cho rằng các công nghệ này ổn định và phổ biến như thế nào Học MERN stack sẽ giúp bạn trở thành full-stack developer. Nhu cầu đối với các nhà phát triển ngăn xếp MERN cũng rất cao. Tuy nhiên, cần có thời gian để trở thành một nhà phát triển ngăn xếp MERN giỏi. Vì vậy, trước khi tìm hiểu các công nghệ như React hay Node. js, điều quan trọng là phải đảm bảo rằng các nguyên tắc cơ bản của bạn vững chắc. Rất nhiều nhà phát triển không thể trở thành nhà phát triển ngăn xếp MERN giỏi vì họ thiếu kiến thức cơ bản về JavaScript Nếu bạn là người học trực quan và có chút thời gian rảnh rỗi, hãy xem video hướng dẫn toàn diện về ngăn xếp MERN này Thiết lập máy chủ với Express. js và nút. jsBản trình diễn này được thiết kế để làm nổi bật thiết lập MERN. Mục tiêu là phát triển một dự án đơn giản với cấu trúc tốt nhất có thể để bạn có thể sử dụng nó như một bản soạn sẵn và nâng cao các dự án ngăn xếp MERN của bạn để đáp ứng các tiêu chuẩn của ngành Để bắt đầu hướng dẫn ngăn xếp MERN của chúng tôi, chúng tôi sẽ chỉ cho bạn cách thiết lập máy chủ với Express. js và nút. js khởi tạo gói npmĐể tạo một thư mục dự án, hãy nhập thư mục thông qua thiết bị đầu cuối, sau đó chạy $ npm install $ npm run app5. Sau đó, nó sẽ hỏi bạn một số câu hỏi về tên gói, phiên bản, điểm vào, v.v. Nhấn $ npm install $ npm run app6 nếu bạn muốn giữ mặc định. Sau đó, bạn sẽ nhận được một cái gì đó như thế này Chọn $ npm install $ npm run app7 và bạn đã sẵn sàng. Thao tác này sẽ tạo một tệp có tên $ npm install $ npm run app8 Cài đặt các phụ thuộcTiếp theo, chúng tôi sẽ thêm một số phụ thuộc với $ npm install $ npm run app9. Nhập hoặc sao chép lệnh trên và nhấn nút Enter. Bạn sẽ thấy một cái gì đó như thế này Đây là những gì chúng tôi nhận được trong đoạn mã trên
Bây giờ, chúng ta sẽ thêm gật đầu như một phụ thuộc // default.json { "mongoURI": "mongodb+srv://mern123:4. Nếu bạn không muốn thêm phần này, bạn có thể bỏ qua nó - đó là tùy chọn. Cài đặt nó với // default.json { "mongoURI": "mongodb+srv://mern123:5. Để sử dụng gật đầu, hãy thêm // default.json { "mongoURI": "mongodb+srv://mern123:6 vào thẻ // default.json { "mongoURI": "mongodb+srv://mern123:7 của bạn bên dưới tệp $ npm install $ npm run app8 Nodemon là một tiện ích sẽ theo dõi mọi thay đổi trong nguồn của bạn và tự động khởi động lại máy chủ của bạn. // default.json { "mongoURI": "mongodb+srv://mern123:9 là điểm đầu vào cho ứng dụng. Điều quan trọng nữa là xác định tập lệnh // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));0 ở đây với // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));1. Điều này sẽ xác định tập lệnh bắt đầu của ứng dụng Sau đó, $ npm install $ npm run app8 của bạn sẽ trông như thế này Đặt điểm vàoBây giờ, hãy tạo một tệp có tên // default.json { "mongoURI": "mongodb+srv://mern123:9 cho điểm vào của chúng tôi. Bạn có thể tạo cái này từ thư mục dự án bằng lệnh // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));4 (trên macOS) Sau đó, dán đoạn mã sau // app.js const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`)); Sau đó, chạy lệnh // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));5. Bạn sẽ thấy // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));6. Bạn cũng có thể kiểm tra nó từ trình duyệt bằng cách mở trình duyệt và nhập // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));7 Tại thời điểm này, nếu chúng tôi thay đổi bất cứ điều gì, chúng tôi sẽ cần khởi động lại máy chủ theo cách thủ công. Tuy nhiên, nếu chúng tôi thiết lập gật đầu, thì chúng tôi không phải khởi động lại nó mỗi lần. Nodemon sẽ theo dõi nếu có bất kỳ thay đổi nào và tự động khởi động lại máy chủ Vì vậy, những gì bạn cần làm là thay đổi một chút đối với tập lệnh trong tệp $ npm install $ npm run app8 của chúng tôi. Xem bên dưới // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } } Bây giờ, bạn có thể chạy dự án của mình bằng lệnh // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));9. Nếu bạn gặp bất kỳ lỗi nào tại thời điểm này, hãy chạy các lệnh bên dưới $ npm install $ npm run app Bạn sẽ thấy những thay đổi sau trong thiết bị đầu cuối của mình nếu mọi thứ suôn sẻ Quản lý cơ sở dữ liệu với MongoDBBây giờ, đã đến lúc thiết lập cơ sở dữ liệu MERN của chúng ta với MongoDB. Để đơn giản, chúng tôi sẽ sử dụng MongoDB Atlas. Đầu tiên, hãy tạo một tài khoản tại đây. Sau khi tạo tài khoản, bạn sẽ thấy như thế này Nhấp vào phần Dự án 0 (trên cùng bên trái) và bạn sẽ thấy nút Tạo dự án mới. Tạo một dự án và chọn dự án. Bây giờ, hãy nhấp vào nút Build a Cluster từ dự án bạn đã tạo. Nó sẽ cho bạn thấy tất cả các thông tin Ở phía dưới, bạn sẽ thấy một phần có tên là Tên cụm, nhấp vào đó và nhập tên cho cơ sở dữ liệu, sau đó nhấn nút Tạo cụm. Sau hai đến ba phút, nếu mọi thứ suôn sẻ, bạn sẽ tìm thấy một cái gì đó như thế này Nhấp vào nút KẾT NỐI và điền vào biểu mẫu tên người dùng và mật khẩu cho cơ sở dữ liệu của bạn Bây giờ, chọn nút Tạo người dùng MongoDB. Bạn cũng có thể chọn địa chỉ IP hiện tại của mình hoặc một địa chỉ IP khác; . Bây giờ, nếu bạn làm theo nút KẾT NỐI hoặc nút Chọn phương thức kết nối, bạn sẽ thấy một số phương thức khác nhau. Chọn cho phù hợp Trong trường hợp này, hãy chọn phần Kết nối ứng dụng của bạn. Bây giờ, bạn sẽ nhận được liên kết cơ sở dữ liệu của mình, chúng tôi sẽ sử dụng liên kết này trong bước tiếp theo Thêm cơ sở dữ liệu vào dự án của chúng tôiCơ sở dữ liệu của chúng tôi đã sẵn sàng và chúng tôi cần thêm nó vào dự án của mình. Bên trong thư mục // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;0, tạo một thư mục khác có tên là // default.json { "mongoURI": "mongodb+srv://mern123:3 và tạo hai tệp có tên là // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;2 và // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;3 Thêm đoạn mã sau // default.json { "mongoURI": "mongodb+srv://mern123: Chúng tôi cần một chút thay đổi trong tệp // default.json { "mongoURI": "mongodb+srv://mern123:9 của mình để kết nối với cơ sở dữ liệu. Cập nhật // default.json { "mongoURI": "mongodb+srv://mern123:9 của bạn với cái này // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`)); Bây giờ, bạn có thể chạy dự án bằng lệnh // app.js const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect Database connectDB(); app.get('/', (req, res) => res.send('Hello world!')); const port = process.env.PORT || 8082; app.listen(port, () => console.log(`Server running on port ${port}`));9. Bạn nên xem những điều sau đây Tuyệt vời. Cho đến nay, chúng tôi đang đi đúng hướng và cơ sở dữ liệu của chúng tôi đã được kết nối thành công. Bây giờ, đã đến lúc hoàn thành thiết lập tuyến đường và sau đó, chúng ta sẽ xem cách tạo API RESTful Xây dựng API RESTful với ngăn xếp MERNĐể bắt đầu, hãy tạo một thư mục có tên // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;7. Trong đó, tạo một thư mục khác có tên // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;8, thư mục này sẽ chứa tất cả các API của chúng tôi. Bên trong thư mục // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;8, tạo một tệp có tên // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);0. Chúng tôi sẽ tạo một số API tại đây để hiển thị cách thức hoạt động của nó trong giây lát Hơn 200 nghìn nhà phát triển sử dụng LogRocket để tạo ra trải nghiệm kỹ thuật số tốt hơnTìm hiểu thêm →Bây giờ, cập nhật // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);0 của bạn với đoạn mã sau // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router; Mô hình cơ sở dữ liệuĐể tương tác với cơ sở dữ liệu của chúng tôi, chúng tôi cần tạo một mô hình cho từng tài nguyên của mình. Vì vậy, hãy tạo một thư mục có tên là // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);2 trong thư mục gốc và bên trong thư mục // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);2, tạo một tệp có tên là // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);4 và cập nhật nó bằng tệp này // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema); Tiếp theo, hãy chạy dự án để xem mọi thứ có ổn không vào thời điểm này và bạn có thể kiểm tra tất cả các API thông qua Postman. Điều quan trọng cần lưu ý là trước khi thử nghiệm API bằng Postman, bạn cần chạy dự án trước Xác thực và ủy quyềnXác thực và ủy quyền là những phần quan trọng của ứng dụng web. Xác thực là quá trình xác minh ai đó cho biết họ là ai. Và ủy quyền là phương pháp kiểm tra cấp độ truy cập của người dùng Khi sử dụng một nút. js và React frontend, hầu hết thời gian, các nhà phát triển có xu hướng sử dụng JWT làm phương thức xác thực. JWT là viết tắt của JSON Web Tokens. JWT là các chuỗi được mã hóa và an toàn cho URL có thể chứa lượng dữ liệu không giới hạn Trong hầu hết các trường hợp, giao diện người dùng React sẽ gửi JWT đến phần phụ trợ. Chương trình phụ trợ xác minh mã thông báo và nếu mã thông báo hợp lệ, chương trình phụ trợ sẽ thực hiện các hoạt động được yêu cầu. Hãy xem video dưới đây để tìm hiểu thêm về cách triển khai xác thực cho ứng dụng của bạn Xây dựng giao diện người dùngCàng xa càng tốt. Bây giờ chúng tôi đã thiết lập phần phụ trợ của mình, đã đến lúc chuyển sang phần giao diện người dùng của hướng dẫn ngăn xếp MERN này. Trong phần này, chúng ta sẽ sử dụng React để xây dựng giao diện người dùng. Chúng tôi sẽ sử dụng Tạo ứng dụng phản ứng để tạo thiết lập tệp ban đầu của chúng tôi Chúng tôi cũng sẽ sử dụng webpack và Babel để đóng gói các mô-đun và biên dịch JavaScript tương ứng. Nếu bạn không biết rõ về webpack hoặc Babel, không vấn đề gì; . Chúng được định cấu hình sẵn và ẩn để bạn có thể tập trung vào mã Chỉ cần tạo một dự án, và bạn đã sẵn sàng để bắt đầu. Bạn cũng sẽ cần bất kỳ phiên bản Node nào. js lớn hơn v8. 10 và bất kỳ phiên bản nào của npm lớn hơn v5. 6 được cài đặt trên máy phát triển cục bộ của bạn Thiết lập Tạo ứng dụng ReactĐặt bất kỳ thư mục nào bằng thiết bị đầu cuối nơi bạn muốn giữ tất cả các tệp của dự án này và chạy // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);5 để lấy tệp thiết lập ban đầu Bạn có thể thay thế // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);6 bằng bất cứ thứ gì bạn muốn sử dụng làm tên dự án của mình. Ví dụ: tên dự án của tôi là // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);7 và lệnh của tôi là // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);8
Trước khi sử dụng bất kỳ lệnh tích hợp nào, chúng ta cần vào bên trong thư mục dự án với // models/Book.js const mongoose = require('mongoose'); const BookSchema = new mongoose.Schema({ title: { type: String, required: true }, isbn: { type: String, required: true }, author: { type: String, required: true }, description: { type: String }, published_date: { type: Date }, publisher: { type: String }, updated_date: { type: Date, default: Date.now } }); module.exports = Book = mongoose.model('book', BookSchema);9 Bây giờ chúng ta đang ở trong thư mục dự án, chúng ta có thể sử dụng các lệnh có sẵn đó. Nếu bạn đang sử dụng Sợi, hãy nhập 0. Nếu bạn đang sử dụng npm, hãy sử dụng 1 Để chạy ứng dụng ở chế độ phát triển, bạn có thể sử dụng bất kỳ lệnh nào ở trên và bạn sẽ thấy thông báo sau trong thiết bị đầu cuối của mình Bây giờ, hãy mở 2 để xem nó trong trình duyệt. Trang này sẽ tự động tải lại nếu bạn thay đổi mã Bên trong thư mục dự án, cấu trúc tệp ban đầu của chúng tôi sẽ trông như thế này Thêm Bootstrap và Font Awesome vào ứng dụng React của bạnChúng tôi đã có tệp thiết lập ban đầu cho phần giao diện người dùng. Bây giờ, chúng ta có thể bắt đầu tích hợp backend với frontend của mình. Trước đó, tôi muốn thêm CDN của Bootstrap và Font Awesome vào dự án của mình Mở tệp có tên 3, nằm trong thư mục chung 4 và thay thế mọi thứ bằng mã sau
Frontend của chúng tôi sẽ có các tính năng sau
Bây giờ, sử dụng lệnh sau để thêm một số phụ thuộc cần thiết $ npm install --save react-router-dom $ npm install --save axios Tại sao lại là Axios?Axios là ứng dụng khách HTTP nhẹ dành cho Node. js và trình duyệt, tương tự như Fetch API. Axios là thư viện async/await dựa trên lời hứa dành cho mã không đồng bộ có thể đọc được. Chúng tôi có thể dễ dàng tích hợp nó với React và dễ dàng sử dụng trong bất kỳ khung giao diện người dùng nào. Chúng tôi sẽ gọi các API của mình thông qua Axios Có nhiều lý do tại sao Axios được sử dụng rộng rãi. Một trong những lợi ích lớn nhất của Axios là khả năng tương thích ngược. Các trình duyệt cũ như IE11 cũng có thể dễ dàng chạy Axios vì gói phát hành 5 bên trong Axios cũng tự động xâu chuỗi tải trọng khi gửi yêu cầu. Tuy nhiên, khi bạn đang sử dụng Fetch API, điều quan trọng là bạn phải chuyển đổi tải trọng thành JSON Tệp $ npm install $ npm run app 4Tại thời điểm này, tệp $ npm install $ npm run app8 của chúng ta phải tương tự (nhưng có thể khác) với mã bên dưới // MERN_A_to_Z_Client - package.json { "name": "mern_a_to_z_client", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.2.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.4.5", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } Tạo tập tin thành phầnBên trong thư mục 8 (_______52_______9), tạo một thư mục khác có tên là $ npm install --save react-router-dom $ npm install --save axios0 và bên trong đó, tạo năm tệp khác nhau
Chúng tôi sẽ làm việc với năm tệp này một lát sau Các thành phần chức năng và React HookCác thành phần chức năng phản ứng là một bổ sung tương đối mới hơn cho khung. Trước đó, chúng tôi chỉ có các thành phần dựa trên lớp. Một thành phần chức năng trong React về cơ bản là một hàm JavaScript trả về phần tử React hoặc JSX. Một thành phần chức năng có thể được viết bằng từ khóa thông thường hoặc chức năng mũi tên. Đạo cụ dựa trên đối số chức năng. Một thành phần chức năng chỉ có thể được sử dụng trên các tệp khác sau khi xuất chúng // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }0 Chức năng hiển thị ở trên là một thành phần chức năng React hợp lệ. Trong hướng dẫn này, chúng ta sẽ sử dụng các thành phần chức năng của React. Để tìm hiểu sâu hơn về các thành phần chức năng của React, hãy xem bài viết này để tìm hiểu thêm Trước phản ứng v16. 8, các nhà phát triển chỉ được phép quản lý trạng thái và các tính năng khác của React trong các thành phần dựa trên lớp. Trong phản ứng v16. 8, nhóm React đã giới thiệu Hook. Móc cho phép nhà phát triển quản lý mã và các tính năng khác của React bên trong một thành phần chức năng Kiểm tra cheat sheet của chúng tôi để biết thêm thông tin về React Hooks Thiết lập tuyến đườngMở thư mục $ npm install --save react-router-dom $ npm install --save axios6 bên trong thư mục 8 ( $ npm install --save react-router-dom $ npm install --save axios8) và thay thế bằng mã sau // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }1 Ở đây, chúng tôi định nghĩa tất cả các // routes/api/books.js const express = require('express'); const router = express.Router(); // Load Book model const Book = require('../../models/Book'); // @route GET api/books/test // @description tests books route // @access Public router.get('/test', (req, res) => res.send('book route testing!')); // @route GET api/books // @description Get all books // @access Public router.get('/', (req, res) => { Book.find() .then(books => res.json(books)) .catch(err => res.status(404).json({ nobooksfound: 'No Books found' })); }); // @route GET api/books/:id // @description Get single book by id // @access Public router.get('/:id', (req, res) => { Book.findById(req.params.id) .then(book => res.json(book)) .catch(err => res.status(404).json({ nobookfound: 'No Book found' })); }); // @route GET api/books // @description add/save book // @access Public router.post('/', (req, res) => { Book.create(req.body) .then(book => res.json({ msg: 'Book added successfully' })) .catch(err => res.status(400).json({ error: 'Unable to add this book' })); }); // @route GET api/books/:id // @description Update book // @access Public router.put('/:id', (req, res) => { Book.findByIdAndUpdate(req.params.id, req.body) .then(book => res.json({ msg: 'Updated successfully' })) .catch(err => res.status(400).json({ error: 'Unable to update the Database' }) ); }); // @route GET api/books/:id // @description Delete book by id // @access Public router.delete('/:id', (req, res) => { Book.findByIdAndRemove(req.params.id, req.body) .then(book => res.json({ mgs: 'Book entry deleted successfully' })) .catch(err => res.status(404).json({ error: 'No such a book' })); }); module.exports = router;7. Đối với một định nghĩa đường dẫn cụ thể, thành phần tương ứng của nó sẽ được hiển thị. Chúng tôi chưa triển khai các tệp và thành phần này — chúng tôi vừa hoàn thành thiết lập đường dẫn Cập nhật tệp CSSTiếp theo, cập nhật tệp CSS có tên là // MERN_A_to_Z_Client - package.json { "name": "mern_a_to_z_client", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.2.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.4.5", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }0 trong thư mục 8 với mã sau // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }2 Thêm các thành phần tính năng của chúng tôiBây giờ, đã đến lúc thêm các thành phần tính năng vào dự án ngăn xếp MERN của chúng tôi. Tệp $ npm install --save react-router-dom $ npm install --save axios1 của chúng tôi chịu trách nhiệm thêm, tạo hoặc lưu sách mới hoặc thông tin về sách $ npm install --save react-router-dom $ npm install --save axios 1Vì vậy, hãy cập nhật $ npm install --save react-router-dom $ npm install --save axios1 với đoạn mã sau // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }3 $ npm install --save react-router-dom $ npm install --save axios 2Thành phần $ npm install --save react-router-dom $ npm install --save axios2 sẽ chịu trách nhiệm hiển thị tất cả sách mà chúng tôi đã lưu trữ trong cơ sở dữ liệu của mình. Cập nhật $ npm install --save react-router-dom $ npm install --save axios2 với mã này // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }4 $ npm install --save react-router-dom $ npm install --save axios 3Ở đây, chúng tôi sử dụng một thành phần chức năng có tên là $ npm install --save react-router-dom $ npm install --save axios3, thành phần này lấy thông tin của một cuốn sách từ $ npm install --save react-router-dom $ npm install --save axios2 và tạo một thẻ cho mỗi cuốn sách. Viết đoạn mã sau để cập nhật tệp $ npm install --save react-router-dom $ npm install --save axios3 của bạn // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }5
Thành phần // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }03 có một nhiệm vụ. nó hiển thị tất cả thông tin chúng tôi có về bất kỳ cuốn sách nào. Chúng tôi có cả hai nút // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }04 và // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }05 ở đây để truy cập // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }6 $ npm install --save react-router-dom $ npm install --save axios 5$ npm install --save react-router-dom $ npm install --save axios5, như tên gọi của nó, chịu trách nhiệm cập nhật thông tin của sách. Nút Chỉnh sửa sách sẽ kích hoạt thành phần này thực hiện. Sau khi nhấp vào Chỉnh sửa sách, chúng tôi sẽ thấy một biểu mẫu có thông tin cũ, chúng tôi sẽ có thể chỉnh sửa hoặc thay thế // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }7 Kết nối và chạy frontend với backendChúng tôi vừa triển khai tất cả các thành phần của mình. Bây giờ, chúng tôi cần một chút thay đổi trong dự án phụ trợ phía máy chủ của chúng tôi Nếu chúng tôi cố gắng gọi API phụ trợ của mình từ phần giao diện người dùng, nó sẽ báo lỗi // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }8 Để giải quyết vấn đề này, chúng tôi cần cài đặt // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }08 trong dự án phía máy chủ phụ trợ của chúng tôi. Chuyển đến thư mục dự án và chạy // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }09 Bây giờ, hãy cập nhật // default.json { "mongoURI": "mongodb+srv://mern123:9, điểm vào của phụ trợ với đoạn mã sau // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }9 Điều quan trọng nữa là bạn phải thêm dòng này, // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }11. Phương pháp // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }12 cho phép Express đọc dữ liệu được gửi bằng yêu cầu // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }13 hoặc // package.json { "name": "mern_a_to_z", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "app": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git" }, "author": "Nur Islam", "license": "MIT", "bugs": { "url": "https://github.com/nurislam03/MERN_A_to_Z/issues" }, "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme", "dependencies": { "body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.5.15", "validation": "0.0.1" }, "devDependencies": { "nodemon": "^1.19.1" } }14. Nó được sử dụng để nhận dạng các đối tượng đến dưới dạng các đối tượng JSON Chạy frontend và backendThực hiện theo các bước bên dưới để chạy cả giao diện người dùng và phụ trợ của ví dụ ngăn xếp MERN của chúng tôi Đầu tiên, chạy máy chủ (bên trong thư mục dự án) $ npm install $ npm run app0 Nếu bạn gặp bất kỳ lỗi nào, hãy làm theo các lệnh bên dưới (bên trong thư mục dự án) $ npm install $ npm run app Để chạy ứng dụng khách, hãy chạy lệnh bên dưới từ thư mục dự án giao diện người dùng $ npm install $ npm run app2 Nếu bạn gặp lại lỗi, hãy làm theo các lệnh tương tự bên dưới $ npm install $ npm run app3 Thử nghiệm ứng dụng ngăn xếp MERN của chúng tôi trong trình duyệtHãy kiểm tra mọi thứ trong trình duyệt. mở http. //máy chủ cục bộ. 3000 trong trình duyệt của bạn. Giờ đây, bạn có thể thêm sách, xóa sách, hiển thị danh sách sách và chỉnh sửa sách. Các tuyến đường sau đây nên thực hiện tương ứng Thêm một cuốn sách mới http. //máy chủ cục bộ. 3000/tạo sách Hiển thị danh sách sách http. //máy chủ cục bộ. 3000/ Hiển thị thông tin của bất kỳ cuốn sách nào http. //máy chủ cục bộ. 3000/show-book/. nhận dạng Cập nhật thông tin sách http. //máy chủ cục bộ. 3000/sửa-sách/. Tôi Phần kết luậnChúc mừng. Bạn đã hoàn thành xuất sắc hướng dẫn ngăn xếp MERN này. Bạn có thể truy cập GitHub của tôi để xem các phần phía máy chủ và phía máy khách của hướng dẫn ngăn xếp MERN này. Bạn cũng có thể tìm thấy repo hoàn chỉnh cho ứng dụng mẫu ngăn xếp MERN của chúng tôi tại đây Làm cách nào để lấy dữ liệu từ MongoDB bằng axios?Sử dụng Mongoose và AXIOS để tải dữ liệu APU lên MongoDB . Đảm bảo bạn đã cài đặt nodejs và NPM, NPM đi kèm với nodejs npm cài đặt cầy mangut axios Yêu cầu các gói trong chỉ mục của bạn. . Nhận mã thông báo API và URL yêu cầu (Tôi sẽ sử dụng URL API kho lưu trữ của mình) Kết nối với DB và lấy dữ liệu từ GitHub Làm cách nào để tìm nạp dữ liệu từ MongoDB đến giao diện người dùng?Cách lấy dữ liệu từ mongodb trong Node js và hiển thị trong HTML (ejs) . Bước 1 – Tạo ứng dụng Node Express js Bước 2 – Cài đặt phụ thuộc cầy mangut flash ejs body-parser Bước 3 – Kết nối ứng dụng với MongoDB Bước 4 – Tạo mô hình Bước 5 – Tạo các tuyến đường Bước 6 – Tạo Bảng HTML và Danh sách Hiển thị Làm cách nào để gửi dữ liệu từ phản ứng tới MongoDB bằng axios?Ví dụ về yêu cầu HTTP GET, POST của React Axios . Bước 1. Thiết lập ứng dụng React Bước 2. Thiết lập thành phần phản ứng Bước 3. Bật định tuyến Bước 4. Tạo biểu mẫu người dùng với Bootstrap Bước 5. Xây dựng máy chủ nút với Express Bước 6. Khai báo lược đồ Mongoose Bước 7. Định cấu hình các tuyến đường cao tốc Bước 8. Định cấu hình tệp máy chủ Làm cách nào để lấy dữ liệu từ phụ trợ đến giao diện người dùng trong phản ứng bằng axios?nhập React,{useEffect,useState} từ 'reac'; . /Ứng dụng. css'; . bài đăng ("http. //máy chủ cục bộ. 8000"). . phản ứng các hình thức trục |