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
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
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'));
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);
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;
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> <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> <td>{{ article._id }}</td> <td>{{ article.title }}</td> <td>{{ article.author }}</td> <td>{{ article.created_at }}</td> <td>{{ article.updated_at }}</td> <td> <button>Edit</button> <button>Delete</button> </td> </tr> </tbody> </table> <div> <form> <input> <input> <textarea></textarea> <button>{{ 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> 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>
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
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!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use
