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

PHPz
Release: 2023-04-05 14:23:01
Original
1005 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template