Cara Membina Aplikasi Dengan Node.js
Node.js ialah persekitaran masa jalan yang membolehkan anda menjalankan kod JavaScript pada bahagian pelayan untuk membina aplikasi bahagian pelayan. Ia berfungsi dengan baik untuk mencipta aplikasi yang pantas dan berskala.
Dalam artikel ini, saya akan menggunakan apl pengurusan acara ringkas sebagai contoh untuk menunjukkan kepada anda cara membina aplikasi menggunakan Node.js, Express.js dan MongoDB.
Pada akhirnya, anda akan tahu cara menyediakan projek Node.js, mencipta pelayan dengan Express.js, menunjukkan halaman dinamik dengan JavaScript terbenam dan menyambung ke pangkalan data MongoDB untuk mengendalikan data anda.
Apa yang Anda Akan Pelajari
- Menyediakan projek Node.js
- Membuat pelayan dengan Express.js
- Memaparkan halaman dinamik dengan ejs
- Menyambung ke pangkalan data MongoDB
- Mencipta model dan skema untuk data anda
- Mengendalikan permintaan dan respons HTTP
Prasyarat
- Node.js dipasang pada sistem anda.
- Pemahaman yang baik tentang MongoDB.
- Editor kod yang anda suka, seperti Kod Visual Studio atau Teks Sublime.
Langkah 1: Sediakan Persekitaran Pembangunan Anda
Pasang Node.js dan npm
Pertama, anda perlu memuat turun dan memasang Node.js. Kemudian anda boleh mengesahkan pemasangan dengan menjalankan: nod -v dan npm -v.
Mulakan Projek Baru
Buat direktori baharu untuk projek anda. Kemudian mulakan projek dengan npm: npm init -y dalam terminal anda.
mkdir event-app cd event-app npm init -y
Menjalankan npm init -y mencipta fail package.json, seperti yang ditunjukkan di atas. Fail ini penting. Ia menyimpan dan menjejaki semua perpustakaan pihak ketiga (pergantungan) yang diperlukan untuk aplikasi anda.
Langkah 2: Sediakan Pelayan
Untuk menyediakan pelayan anda, buat fail yang dipanggil server.js atau app.js. Ini adalah nama biasa. Mereka digunakan untuk sifat deskriptif mereka. Tetapi, anda boleh menamakan fail itu apa sahaja yang anda suka.
Fail server.js akan digunakan untuk mencipta pelayan yang akan digunakan untuk mengurus, mengawal dan menghala ke halaman yang diperlukan dalam aplikasi kami.
Langkah 3: Pasang dan Sediakan Express.js
Express.js ialah rangka kerja aplikasi web yang popular untuk Node.js dan perpustakaan pihak ketiga yang kami gunakan dalam aplikasi kami.
Express memudahkan pengendalian dan definisi pelbagai laluan untuk permintaan HTTP. Ia membolehkan anda mengurus penghalaan aplikasi dan menyambungkannya ke pelayan.
Untuk menggunakan Express:
Pasang Express.js dengan menjalankan arahan berikut dalam terminal anda:
npm install express
Memerlukan Express dalam fail server.js anda.
const express = require('express')
Inisialisasikan Express supaya anda boleh menggunakannya dalam aplikasi anda.
const app = express()
Buat laluan penghalaan untuk mendapatkan permintaan HTTP.
//routing path app.get('/', (req, res) => { res.send('Hello World!'); });
Akhir sekali, kita perlu memastikan sambungan ke pelayan disediakan dengan betul. Apabila kita memulakan pelayan di terminal, ia akan dibuka dalam penyemak imbas.
Untuk melakukan ini, gunakan kaedah listen().
// Start the server app.listen(3000, () => { console.log('Server started on port 3000'); });
Kaedah ini akan mendengar() permintaan daripada pelayan.
Berikut ialah proses kod lengkap:
const express = require('express'); // Next initialize the application const app = express(); // routing path app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server app.listen(3000, () => { console.log('Server started on port 3000'); });
Nota: Laluan penghalaan di atas hanya untuk tujuan ujian untuk mengesahkan bahawa pelayan berfungsi dan disambungkan. Kami akan menyediakan fail lain untuk apl acara yang kami buat.
Dengan Express.js dipasang dalam aplikasi anda, anda kini boleh membuat pelayan yang akan mengendalikan semua penghalaan dan sambungan anda.
Untuk memulakan pelayan, pergi ke terminal anda.
Gunakan nod kata kunci, kemudian taip --watch yang merupakan bendera untuk dimulakan dan mulakan semula pelayan secara automatik apabila anda membuat perubahan:
node --watch server.js
Atau anda boleh memasang nodemon untuk tujuan yang sama. nodemon mengesan perubahan dalam direktori dan memulakan semula aplikasi anda.
npm install -g nodemon
Kemudian jalankan pelayan anda dengan:
nodemon server.js
Langkah 4: Cipta Templat Dinamik
Kami memerlukan enjin templat untuk memaparkan kod HTML dalam penyemak imbas menggunakan Node.js. Kami akan menggunakan ejs (JavaScript Terbenam) untuk tutorial ini tetapi terdapat yang lain seperti Pug (dahulunya dikenali sebagai Jade) dan Express Handlebar, yang turut memaparkan HTML pada pelayan.
ejs membolehkan anda membenamkan JavaScript dalam HTML untuk mencipta halaman web dinamik.
Untuk memasang ejs, jalankan:
npm install ejs
Untuk menyediakan ejs dalam server.js, perlukan dan tetapkan ejs sebagai enjin templat:
const express = require('express'); const app = express(); app.set('view engine', 'ejs');
Dengan persediaan ini, anda kini boleh mendayakan pemaparan dinamik kod HTML dalam aplikasi Node.js anda.
Langkah 5: Simpan Data Anda ke MongoDB
Untuk menyimpan data yang anda cipta untuk aplikasi anda, anda akan menggunakan MongoDB.
MongoDB is a "Not Only SQL" (NoSQL) database that's designed for storing document collections. Traditional SQL databases organize data into tables, but MongoDB is optimised for handling large volumes of data.
To read more about this, check out this article.
Step 6: Connect to the Database
Now we need to connect to the database which will be MongoDB for this tutorial.
Using MongoDB provides you with a Uniform Resource Locator (URL) to connect to your application. This URL connect you and acts as a communicator between the database and your application.
How to get the URL
To get the URL, follow these simple steps:
Sign Up/Log In: Go to the MongoDB website and sign up for an account or log in if you already have one.
Create a Cluster: Once logged in, create a new cluster. This will set up your database.
Connect to Your Cluster: After your cluster is created, click the "Connect" button.
Choose a Connection Method: Select "Connect your application".
Copy the Connection String: MongoDB will provide a connection string (URL) like this:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority
6.Replace the Placeholders: Replace with your actual username, password, and database name.
Now that you have the URL, you can easily connect to your database.
To make this connection easier, we will use a tool called Mongoose.
What is Mongoose?
Mongoose is a JavaScript library that makes it easier to work with MongoDB in a Node.js environment. It provides a simple way to model your data. You can also define schemas, do data validation, and build queries.
How to make a connection
MongoDB has already provided you with a URL for connection. Now you'll use Mongoose to send your documents to the database.
To use Mongoose in your project, follow these steps:
Install Mongoose using npm.
npm i mongoose
In your server.js file, you need to require Mongoose to use it as a connector to the database.
const mongoose = require('mongoose');
After you require Mongoose, you need to define the connection URL provided in your server.js file.
server.js:
const mongoose = require('mongoose'); // Replace <username>, <password>, and <dbname> with your actual credentials const dbURL = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority'; mongoose .connect(process.env.dbURL) .then((result) => { console.log('Connected to MongoDB'); app.listen(3000, () => { console.log('Server started on port 3000'); }); }) .catch((err) => { console.error('Could not connect to MongoDB:', err); });
This setup ensures that Mongoose acts as the connector. It connects your application to the MongoDB database.
Step 7: Create the Model for the Document Structure
Next, we need to create a model document called a Schema so that when you post data to your database it will be saved accordingly.
To create this model:
- Create a folder named models to keep your application organized.
- Inside the model's folder, create a file called event.js.
In the event.js file, you will use Mongoose to define the schema for the event documents. You'll specify the structure and data types for the documents you will send to your database.
Here's the event.js file created inside the model folder:
const mongoose = require('mongoose'); // Schema const EventSchema = new mongoose.Schema( { title: { type: String, required: true, }, date: { type: Date, required: true, }, organizer: { type: String, required: true, }, price: { type: String, required: true, }, time: { type: String, required: true, }, location: { type: String, required: true, }, description: { type: String, required: true, }, }, { timestamps: true } ); const Event = mongoose.model('event', EventSchema); module.exports = Event;
When this is done, export so you can use it in your server.js file by simply using the require keyword.
With the schema created, it can now be exported to the server.js file.
Your server.js will look like this:
const express = require('express'); const ejs = require('ejs'); const mongoose = require('mongoose'); const Event = require('../models/Events');// the event.js file
Step 8: Create HTML Pages
As we talked about earlier, we're using ejs in step 4 to render HTML code, allowing us to view the code in the browser.
Form Page
First, let's create a form page. With the form page created, you'll be able to make POST requests which will enable you to send data to your MongoDB database.
To create a basic form, ensure it includes:
An action attribute which specifies the route to send the data.
A method attribute which specifies the HTTP request method – in this case, the POST request.
A basic form:
<form action="/submit-event" method="POST"> <h2>Event Creation Form</h2> <label for="title">Title</label> <input type="text" id="title" name="title" required> <label for="date">Date</label> <input type="date" id="date" name="date" required> <label for="organizer">Organizer</label> <input type="text" id="organizer" name="organizer" required> <label for="price">Price</label> <input type="text" id="price" name="price" required> <label for="time">Time</label> <input type="text" id="time" name="time" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="description">Description</label> <textarea id="description" name="description" rows="4" required></textarea> <button type="submit">Submit</button> </form>
NB: Make sure to add the name attribute to each input, or it won't post.
The form created above will let you post data to the specified route. You will then process and store it in your database.
Here's the result:
After creating the form page, we need to go back to the server.js file and create a POST request to handle the form submission.
server.js file:
// posting a data app.post('/submit-event', (req, res) => { const event = new Event(req.body); event.save() .then((result) => { res.redirect('/'); }) .catch((err) => { console.error(err); }); });
The Homepage
Now that the form can post data to the database, we can create the homepage to display the created events in the browser.
First, in your server.js file, you need to create a function. It will fetch all the events posted from the form and stored in the database.
Here’s how to set it up:
This is a function created at server.js to fetch all data from the database:
// To get all the event router.get('/', (req, res) => { Event.find() .then((result) => { res.render('index', { title: 'All event', events: result }) }) .catch((err) => { console.error(err); }) })
Next, we will dynamically loop through each part using a forEach loop in the homepage file. Since we are using ejs, the HTML file extension will be .ejs.
<div> <h2>All events</h2> <div> <% if (events.length > 0) { %> <% events.forEach(event => { %> <div> <h3><%= event.title %></h3> <p><%= event.description %></p> <a href="/event/<%= event.id %>"> Read More </a> </div> <% }) %> <% } else { %> <p>No events are available at the moment.</p> <% } %> </div> </div>
Step 9: Create Partials
Remember that you installed ejs into your application to facilitate more dynamic components. It allows you to break your code down further to be more dynamic.
To further organize your code, you'll use something called Partials.
Partials let you break down your code into scalable, modular, and manageable parts, keeping your HTML organized.
First, let's create a partial for the navbar.
How to Create a Partial:
Inside your views folder, create a new folder named Partials
Inside the partials folder, create a new file called nav.ejs.
Cut out the navbar code from your homepage file and paste it into nav.ejs.
Example:
First, create the Partials folder and file:
Use the <%- include() %> syntax from ejs to include the nav.ejs partial across pages in your application where you want the navbar to appear.
Here's the code: <!DOCTYPE html> <html lang="en"> <%- include('./partial/head.ejs') %> <body> <%- include('./partial/nav.ejs') %> <main> hello </main> <%- include('./partial/footer.ejs') %> </body> </html>
With this setup, your HTML code will be organized. It will be easy to manage and update components like the navbar across different pages. You can use this approach on other parts of your application. For example, the head tag, footer tag, and other reusable components.
Step 10: Create an Environment Variable File (.Env)
In this tutorial, we'll upload the project to GitHub. You'll protect your port number and MongoDB URL with secure storage. You'll also use an environment variable file, a configuration file known as .env. This file keeps sensitive information safe. It includes passwords and API URLs and prevents exposure.
Here's how to set it up using Node.js:
First, install the dotenv package.
npm i dotenv
Then create a .env file. Inside it, add your PORT number and MongoDB URL. It should look something like this:
PORT=3000 dbURl='mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority';
Then update your .gitignore file:
/node_modules .env
Adding .env to your .gitignore ensures that it is not included in your GitHub repository. This tells Git to ignore the .env file when uploading your code.
Then in your server.js file, require the dotenv package. Load the variables with this line at the top of the file:
To require it, simply type:
require('dotenv').config();
This way, you don't need to hardcode the PORT number and MongoDB URL in your server.js file. Instead, you can access them using process.env.PORT and process.env.dbURl.
So your server.js file will be cleaner and not messy ??
require('dotenv').config(); const express = require('express'); const ejs = require('ejs'); const mongoose = require('mongoose'); mongoose .connect(process.env.dbURL) .then((result) => { console.log('Connected to MongoDB'); app.listen(3000, () => { console.log('Server started on port 3000'); }); }) .catch((err) => { console.error('Could not connect to MongoDB:', err); });
Further Steps
To expand on this basic application, consider adding features such as:
User authentication
Event search and filter functionality
Event editing and deletion
Notifications for upcoming events
How to Style the Application
If you want to add some styling to your application, follow these steps:
First, create a public folder. Inside this folder, create a style.css file where you will write your custom CSS.
Then in your HTML file, link the style.css file in the
tag as you normally would:<link rel="stylesheet" href="/style.css">
To ensure your CSS file is served correctly, add the following line to your server.js file:
app.use(express.static('public'));
This application uses Tailwind CSS for styling. But using Tailwind is optional. You can use any CSS framework or write custom CSS to achieve your desired layout.
How to Include Images
All images should be stored in the public folder and referenced in your HTML files. You should also ensure that the public folder is correctly set up in your server.js file to serve static files.
Here's an example of how to serve static files in server.js:
const express = require('express'); const app = express(); // Serve static files from the 'public' folder app.use(express.static('public'));
Conclusion
Congratulations! You've built a simple application using Node.js, Express.js, ejs, and MongoDB. With these fundamentals, you can expand and enhance your application to meet more specific needs and features.
Feel free to share your progress or ask questions if you encounter any issues.
Jika anda mendapati artikel ini membantu, kongsikan dengan orang lain yang mungkin juga menganggapnya menarik.
Kekal dikemas kini dengan projek saya dengan mengikuti saya di Twitter, LinkedIn dan GitHub
Terima kasih kerana membaca ?.
Selamat mengekod!
Atas ialah kandungan terperinci Cara Membina Aplikasi Dengan Node.js. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

Titik berikut harus diperhatikan apabila tarikh pemprosesan dan masa di JavaScript: 1. Terdapat banyak cara untuk membuat objek tarikh. Adalah disyorkan untuk menggunakan rentetan format ISO untuk memastikan keserasian; 2. Dapatkan dan tetapkan maklumat masa boleh diperoleh dan tetapkan kaedah, dan ambil perhatian bahawa bulan bermula dari 0; 3. Tarikh pemformatan secara manual memerlukan rentetan, dan perpustakaan pihak ketiga juga boleh digunakan; 4. Adalah disyorkan untuk menggunakan perpustakaan yang menyokong zon masa, seperti Luxon. Menguasai perkara -perkara utama ini secara berkesan dapat mengelakkan kesilapan yang sama.

Penangkapan dan gelembung acara adalah dua peringkat penyebaran acara di Dom. Tangkap adalah dari lapisan atas ke elemen sasaran, dan gelembung adalah dari elemen sasaran ke lapisan atas. 1. Penangkapan acara dilaksanakan dengan menetapkan parameter useCapture addeventlistener kepada benar; 2. Bubble acara adalah tingkah laku lalai, useCapture ditetapkan kepada palsu atau ditinggalkan; 3. Penyebaran acara boleh digunakan untuk mencegah penyebaran acara; 4. Acara menggelegak menyokong delegasi acara untuk meningkatkan kecekapan pemprosesan kandungan dinamik; 5. Penangkapan boleh digunakan untuk memintas peristiwa terlebih dahulu, seperti pemprosesan pembalakan atau ralat. Memahami kedua -dua fasa ini membantu mengawal masa dan bagaimana JavaScript bertindak balas terhadap operasi pengguna.

Perbezaan utama antara modul ES dan Commonjs adalah kaedah pemuatan dan senario penggunaan. 1.Commonjs dimuatkan secara serentak, sesuai untuk persekitaran sisi pelayan Node.js; 2. Modul tidak disengajakan, sesuai untuk persekitaran rangkaian seperti penyemak imbas; 3. Sintaks, modul ES menggunakan import/eksport dan mesti terletak di skop peringkat atas, manakala penggunaan CommonJS memerlukan/modul.exports, yang boleh dipanggil secara dinamik pada runtime; 4.Commonjs digunakan secara meluas dalam versi lama node.js dan perpustakaan yang bergantung kepadanya seperti Express, manakala modul ES sesuai untuk kerangka depan moden dan nod.jsv14; 5. Walaupun ia boleh dicampur, ia boleh menyebabkan masalah dengan mudah.

Mekanisme pengumpulan sampah JavaScript secara automatik menguruskan memori melalui algoritma pembersihan tag untuk mengurangkan risiko kebocoran ingatan. Enjin melintasi dan menandakan objek aktif dari objek akar, dan tidak bertanda dianggap sebagai sampah dan dibersihkan. Sebagai contoh, apabila objek tidak lagi dirujuk (seperti menetapkan pembolehubah kepada null), ia akan dikeluarkan dalam pusingan seterusnya kitar semula. Punca kebocoran memori yang biasa termasuk: ① Pemasa atau pendengar peristiwa yang tidak jelas; ② Rujukan kepada pembolehubah luaran dalam penutupan; ③ Pembolehubah global terus memegang sejumlah besar data. Enjin V8 mengoptimumkan kecekapan kitar semula melalui strategi seperti kitar semula generasi, penandaan tambahan, kitar semula selari/serentak, dan mengurangkan masa menyekat benang utama. Semasa pembangunan, rujukan global yang tidak perlu harus dielakkan dan persatuan objek harus dihiasi dengan segera untuk meningkatkan prestasi dan kestabilan.

Terdapat tiga cara biasa untuk memulakan permintaan HTTP dalam node.js: Gunakan modul terbina dalam, axios, dan nod-fetch. 1. Gunakan modul HTTP/HTTPS terbina dalam tanpa kebergantungan, yang sesuai untuk senario asas, tetapi memerlukan pemprosesan manual jahitan data dan pemantauan ralat, seperti menggunakan https.get () untuk mendapatkan data atau menghantar permintaan pos melalui .write (); 2.AXIOS adalah perpustakaan pihak ketiga berdasarkan janji. Ia mempunyai sintaks ringkas dan fungsi yang kuat, menyokong async/menunggu, penukaran JSON automatik, pemintas, dan lain -lain. Adalah disyorkan untuk memudahkan operasi permintaan tak segerak; 3.Node-Fetch menyediakan gaya yang serupa dengan pengambilan penyemak imbas, berdasarkan janji dan sintaks mudah

Perbezaan antara VAR, LET dan Const adalah skop, promosi dan pengisytiharan berulang. 1.VAR adalah skop fungsi, dengan promosi yang berubah -ubah, yang membolehkan pengisytiharan berulang; 2.Let adalah skop peringkat blok, dengan zon mati sementara, dan pengisytiharan berulang tidak dibenarkan; 3.const juga skop peringkat blok, dan mesti diberikan dengan segera, dan tidak boleh ditugaskan semula, tetapi nilai dalaman jenis rujukan boleh diubah suai. Gunakan const terlebih dahulu, gunakan biarkan apabila menukar pembolehubah, dan elakkan menggunakan var.

Sebab -sebab utama untuk operasi perlahan DOM adalah kos penyusunan semula dan penyusunan semula dan kecekapan akses yang rendah. Kaedah pengoptimuman termasuk: 1. Mengurangkan bilangan akses dan nilai baca cache; 2. Batch membaca dan menulis operasi; 3. Menggabungkan dan mengubah suai, menggunakan serpihan dokumen atau elemen tersembunyi; 4. Elakkan susun atur susun atur dan mengendalikan membaca dan menulis; 5. Rangka Kerja Gunakan atau Kemas Kini Asynchronous Rangka Kerja.
