Home Web Front-end JS Tutorial How to build a full-stack project with Node.js and Vue.js

How to build a full-stack project with Node.js and Vue.js

Apr 05, 2023 pm 01:50 PM

Node.js and Vue.js are two very popular technologies currently. Node.js is a server-side development platform running on JavaScript, while Vue.js is a progressive framework for building user interfaces. The combination of these two technologies can greatly improve the development efficiency and user experience of web applications. In this article, we will use a practical project to show how to use Node.js and Vue.js to build a full-stack web application.

1. Project Introduction

We will develop a simple article publishing and management system. Users can register and log in to publish articles, comment and view articles published by other users. In order to achieve this function, we will use Node.js as the back-end development language and technology framework, Vue.js as the front-end development framework, and MongoDB as the database.

2. Environment setup

Before starting development, you first need to set up the development environment for Node.js, Vue.js and MongoDB in the local environment.

1. Install Node.js: You can download the Node.js installation package from the official website for installation.

2. Install Vue.js: You can use the npm command line tool to install Vue.js. Enter the following command on the command line:

npm install -g vue-cli
Copy after login

3. Install MongoDB: You can download the MongoDB installation package from the official website and install it.

3. Project structure

We divide the project into two parts: front-end and back-end, so we need to create two folders to store the code of these two parts. We can Create a folder named "node-vue-app" in the root directory to store the entire project.

1. Create the backend part

Create a folder named "server" under the "node-vue-app" folder, and create a folder named "server" under the folder. app.js" file, which will serve as our backend service entry file. At the same time, we need to create a folder named "routes" under the "server" folder to store the routing code; and create a folder named "models" under the "server" folder to store the routing code. Data model code.

2. Create the front-end part

Create a folder named "client" under the "node-vue-app" folder. We will carry out front-end development in this folder. You can create a Vue.js project using the command line tools provided by Vue.js:

vue init webpack client
Copy after login

This command will create a folder named "src" under the "client" folder, which will contain All our front-end code.

4. Back-end development

In this case, we will use Express as the back-end framework to complete the development of RESTful API. In the "app.js" file, we need to introduce relevant modules and libraries and initialize the Express application:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/node-vue-app', { useNewUrlParser: true });
mongoose.connection.once('open', () => {
    console.log('connected to database');
});

app.listen(3000, () => console.log('server is running on port 3000'));
Copy after login

1. Define the data model

We need to under the "models" folder Define our data model and create a file named "article.js":

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const articleSchema = new Schema({
    title: String,
    author: String,
    content: String,
    created_at: Date,
    updated_at: Date
});

module.exports = mongoose.model('Article', articleSchema);
Copy after login

In this file, we define a data model named "Article" and define the corresponding data structure .

2. Define routes

Create a file named "articles.js" under the "routes" folder. We will define the article-related routing processing logic in this file:

const express = require('express');
const router = express.Router();
const Article = require('../models/article');

// 获取文章列表
router.get('/', (req, res) => {
    Article.find((err, articles) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ articles });
        }
    });
});

// 获取单篇文章
router.get('/:id', (req, res) => {
    Article.findById(req.params.id, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

// 新增文章
router.post('/', (req, res) => {
    const article = new Article(req.body);
    article.save()
        .then(() => res.json({ success: true }))
        .catch(err => console.log(err));
});

// 更新文章
router.put('/:id', (req, res) => {
    Article.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

// 删除文章
router.delete('/:id', (req, res) => {
    Article.findByIdAndRemove(req.params.id, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

module.exports = router;
Copy after login

In this file, we define all the routing processing logic related to the article, including getting the article list, getting a single article, adding new articles, updating articles and deleting articles.

5. Front-end development

In this case, we will use Vue.js components to complete front-end development. Create a folder named "components" under the "client/src" folder to store Vue.js components. We will create a component named "Articles" under this folder, which will implement articles. List display, addition, editing and deletion:

<template>
    <div class="articles">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Author</th>
                    <th>Created At</th>
                    <th>Updated At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="article in articles" :key="article._id">
                    <td>{{ article._id }}</td>
                    <td>{{ article.title }}</td>
                    <td>{{ article.author }}</td>
                    <td>{{ article.created_at }}</td>
                    <td>{{ article.updated_at }}</td>
                    <td>
                        <button @click="edit(article._id)">Edit</button>
                        <button @click="del(article._id)">Delete</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="form">
            <form @submit.prevent="submit">
                <input type="text" v-model="article.title" placeholder="Title">
                <input type="text" v-model="article.author" placeholder="Author">
                <textarea v-model="article.content" placeholder="Content"></textarea>
                <button type="submit">{{ isNew ? 'Create' : 'Update' }}</button>
            </form>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                articles: [],
                article: {
                    title: '',
                    author: '',
                    content: ''
                },
                isNew: true
            }
        },
        created() {
            this.getArticles();
        },
        methods: {
            getArticles() {
                fetch('/api/articles')
                    .then(res => res.json())
                    .then(data => this.articles = data.articles)
                    .catch(err => console.log(err));
            },
            createArticle() {
                fetch('/api/articles', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.article)
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            this.article = { title: '', author: '', content: '' };
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            updateArticle(id) {
                fetch(`/api/articles/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.article)
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.article) {
                            this.article = { title: '', author: '', content: '' };
                            this.isNew = true;
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            deleteArticle(id) {
                fetch(`/api/articles/${id}`, {
                    method: 'DELETE'
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.article) {
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            submit() {
                if (this.isNew) {
                    this.createArticle();
                } else {
                    this.updateArticle(this.article._id);
                }
            },
            edit(id) {
                const article = this.articles.find(a => a._id === id);
                this.article = { ...article };
                this.isNew = false;
            },
            del(id) {
                const article = this.articles.find(a => a._id === id);
                if (window.confirm(`Are you sure to delete article: ${article.title}?`)) {
                    this.deleteArticle(id);
                }
            }
        }
    }
</script>

<style scoped>
    table {
        border-collapse: collapse;
        width: 100%;
    }
    td, th {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    tr:nth-child(even) {
        background-color: #f2f2f2;
    }
    form {
        display: flex;
        flex-direction: column;
    }
    textarea {
        height: 100px;
    }
    button {
        margin-top: 10px;
        padding: 8px 16px;
        background-color: #1E6FAF;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    button:hover {
        background-color: #15446F;
    }
</style>
Copy after login

In this component, we define a Vue.js component named "Articles" and implement the display, addition and editing of the article list and deletion function. This component calls the back-end API to obtain, create, update and delete articles through the fetch() function.

6. Start the application

After completing the back-end and front-end development, we need to start the application to verify whether our code is working properly. Enter the project root directory in the command line and execute the following commands in the "server" and "client" folders respectively:

npm install
npm start
Copy after login

This command will start the back-end and front-end services respectively and open them in the browser Front-end application. Enter "http://localhost:8080" in your browser to access our article publishing and management system.

7. Summary

The combination of Node.js and Vue.js can help us quickly build a full-stack web application and achieve efficient development and good user experience. In this article, we show how to use Node.js and Vue.js to build a full-stack web application through a practical project. I believe this article can help developers better understand the applications of Node.js and Vue.js.

The above is the detailed content of How to build a full-stack project with Node.js and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles