Heim > Web-Frontend > js-Tutorial > Hauptteil

So erstellen Sie eine Anwendung mit Node.js

WBOY
Freigeben: 2024-08-09 18:44:36
Original
1111 Leute haben es durchsucht

Node.js ist eine Laufzeitumgebung, die es Ihnen ermöglicht, JavaScript-Code auf der Serverseite auszuführen, um serverseitige Anwendungen zu erstellen. Es eignet sich gut zum Erstellen schneller und skalierbarer Anwendungen.

In diesem Artikel verwende ich eine einfache Event-Management-App als Beispiel, um Ihnen zu zeigen, wie Sie eine Anwendung mit Node.js, Express.js und MongoDB erstellen.

Am Ende wissen Sie, wie Sie ein Node.js-Projekt einrichten, einen Server mit Express.js erstellen, dynamische Seiten mit eingebettetem JavaScript anzeigen und eine Verbindung zu einer MongoDB-Datenbank herstellen, um Ihre Daten zu verarbeiten.

Was Sie lernen werden

  • Einrichten eines Node.js-Projekts
  • Erstellen eines Servers mit Express.js
  • Dynamische Seiten mit EJS rendern
  • Herstellen einer Verbindung zu einer MongoDB-Datenbank
  • Erstellen von Modellen und Schemata für Ihre Daten
  • Verarbeitung von HTTP-Anfragen und -Antworten

How to Build an Application With Node.js

Voraussetzungen

  • Node.js ist auf Ihrem System installiert.
  • Ein gutes Verständnis von MongoDB.
  • Ein Code-Editor, den Sie bevorzugen, z. B. Visual Studio Code oder Sublime Text.

Schritt 1: Richten Sie Ihre Entwicklungsumgebung ein

Installieren Sie Node.js und npm

Zuerst müssen Sie Node.js herunterladen und installieren. Anschließend können Sie die Installation überprüfen, indem Sie Folgendes ausführen: node -v und npm -v.

Initialisieren Sie ein neues Projekt

Erstellen Sie ein neues Verzeichnis für Ihr Projekt. Initialisieren Sie dann das Projekt mit npm: npm init -y in Ihrem Terminal.

mkdir event-app
cd event-app
npm init -y
Nach dem Login kopieren

Durch Ausführen von npm init -y wird die Datei package.json erstellt, wie oben gezeigt. Diese Datei ist von entscheidender Bedeutung. Es speichert und verfolgt alle für Ihre Anwendung erforderlichen Bibliotheken (Abhängigkeiten) von Drittanbietern.

Schritt 2: Richten Sie den Server ein

Um Ihren Server einzurichten, erstellen Sie eine Datei mit dem Namen server.js oder app.js. Dies sind gebräuchliche Namen. Sie werden aufgrund ihres beschreibenden Charakters verwendet. Sie können der Datei jedoch einen beliebigen Namen geben.

Die Datei server.js wird verwendet, um einen Server zu erstellen, der zur Verwaltung, Steuerung und Weiterleitung an die erforderliche Seite in unserer Anwendung verwendet wird.

Schritt 3: Express.js installieren und einrichten

Express.js ist ein beliebtes Webanwendungs-Framework für Node.js und eine Bibliothek eines Drittanbieters, die wir in unserer Anwendung verwenden.

Express vereinfacht die Handhabung und Definition verschiedener Routen für HTTP-Anfragen. Damit können Sie das Routing der Anwendung verwalten und sie mit dem Server verbinden.

So verwenden Sie Express:

Installieren Sie Express.js, indem Sie den folgenden Befehl in Ihrem Terminal ausführen:

npm install express
Nach dem Login kopieren

Express in Ihrer server.js-Datei erforderlich.

const express = require('express')
Nach dem Login kopieren

Initialisieren Sie Express, damit Sie es in Ihrer Anwendung verwenden können.

const app = express()
Nach dem Login kopieren

Erstellen Sie einen Routing-Pfad, um die HTTP-Anfrage zu erhalten.

//routing path
app.get('/', (req, res) => {
  res.send('Hello World!');
});
Nach dem Login kopieren

Zuletzt müssen wir sicherstellen, dass die Verbindung zum Server korrekt eingerichtet ist. Wenn wir den Server im Terminal starten, wird er im Browser geöffnet.

Verwenden Sie dazu die Methode listen().

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
Nach dem Login kopieren

Diese Methode hört() auf Anfragen vom Server.

Hier ist der vollständige Codeprozess:

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');
});
Nach dem Login kopieren

Hinweis: Der oben angegebene Routing-Pfad diente nur zu Testzwecken, um zu bestätigen, dass der Server funktioniert und verbunden ist. Wir werden eine andere Datei für die Event-App bereitstellen, die wir erstellen.

Wenn Express.js in Ihrer Anwendung installiert ist, können Sie jetzt einen Server erstellen, der alle Ihre Routings und Verbindungen verwaltet.

Um den Server zu starten, gehen Sie zu Ihrem Terminal.

Verwenden Sie das Schlüsselwort node und geben Sie dann --watch ein, ein Flag zum Starten und automatischen Neustarten des Servers, wenn Sie Änderungen vornehmen:

node --watch server.js
Nach dem Login kopieren

Oder Sie können Nodemon für den gleichen Zweck installieren. nodemon erkennt Änderungen im Verzeichnis und startet Ihre Anwendung neu.

npm install -g nodemon
Nach dem Login kopieren

Dann betreiben Sie Ihren Server mit:

nodemon server.js
Nach dem Login kopieren

Schritt 4: Erstellen Sie eine dynamische Vorlage

Wir benötigen eine Template-Engine, um HTML-Code im Browser mithilfe von Node.js darzustellen. Für dieses Tutorial verwenden wir ejs (Embedded JavaScript), aber es gibt auch andere wie Pug (früher bekannt als Jade) und Express Handler, die ebenfalls HTML auf dem Server rendern.

ejs ermöglicht Ihnen das Einbetten von JavaScript in HTML, um dynamische Webseiten zu erstellen.

Um ejs zu installieren, führen Sie Folgendes aus:

npm install ejs
Nach dem Login kopieren

Um ejs in server.js einzurichten, fordern Sie ejs an und legen Sie es als Template-Engine fest:

How to Build an Application With Node.js

const express = require('express');
const app = express();
app.set('view engine', 'ejs');
Nach dem Login kopieren

Mit diesem Setup können Sie jetzt das dynamische Rendern von HTML-Code in Ihrer Node.js-Anwendung aktivieren.

Schritt 5: Speichern Sie Ihre Daten in MongoDB

Um die Daten, die Sie für Ihre Anwendung erstellen, zu speichern, verwenden Sie 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:

  1. Sign Up/Log In: Go to the MongoDB website and sign up for an account or log in if you already have one.

  2. Create a Cluster: Once logged in, create a new cluster. This will set up your database.

  3. Connect to Your Cluster: After your cluster is created, click the "Connect" button.

  4. Choose a Connection Method: Select "Connect your application".

  5. 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
Nach dem Login kopieren

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
Nach dem Login kopieren

In your server.js file, you need to require Mongoose to use it as a connector to the database.

const mongoose = require('mongoose');
Nach dem Login kopieren

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);
  });
Nach dem Login kopieren

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;
Nach dem Login kopieren

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
Nach dem Login kopieren

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>
Nach dem Login kopieren

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:

How to Build an Application With Node.js

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);
    });
});
Nach dem Login kopieren

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); 
  })
})
Nach dem Login kopieren

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>
Nach dem Login kopieren

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:

How to Build an Application With Node.js

Use the <%- include() %> syntax from ejs to include the nav.ejs partial across pages in your application where you want the navbar to appear.

How to Build an Application With Node.js

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>

Nach dem Login kopieren

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
Nach dem Login kopieren

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';
Nach dem Login kopieren

Then update your .gitignore file:

/node_modules
.env
Nach dem Login kopieren

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();
Nach dem Login kopieren

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);
  });
Nach dem Login kopieren

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">
Nach dem Login kopieren

To ensure your CSS file is served correctly, add the following line to your server.js file:

app.use(express.static('public'));
Nach dem Login kopieren

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'));
Nach dem Login kopieren

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.

Wenn Sie diesen Artikel hilfreich fanden, teilen Sie ihn mit anderen, die ihn möglicherweise auch interessant finden.

Bleiben Sie über meine Projekte auf dem Laufenden, indem Sie mir auf Twitter, LinkedIn und GitHub folgen

Danke fürs Lesen?.

Viel Spaß beim Codieren!

Das obige ist der detaillierte Inhalt vonSo erstellen Sie eine Anwendung mit Node.js. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!