vue前后端实现
Vue 前后端实现方案
Vue 作为前端框架,通常需要与后端服务结合使用。以下是常见的实现方式:
前端实现(Vue)
使用 Vue CLI 或 Vite 创建项目:
npm init vue@latest my-project
cd my-project
npm install
配置 axios 进行 HTTP 请求:
import axios from 'axios';
const api = axios.create({
baseURL: 'http://backend-api.com',
timeout: 5000
});
组件中调用接口:
export default {
methods: {
fetchData() {
api.get('/data').then(response => {
this.data = response.data;
});
}
}
}
后端实现(Node.js + Express)
安装 Express:
npm install express cors
创建基础服务:

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.get('/api/data', (req, res) => {
res.json({ message: "Data from backend" });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
数据库连接(以 MongoDB 为例)
安装 mongoose:
npm install mongoose
配置数据库连接:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});
跨域解决方案
开发环境配置代理(vue.config.js):

module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
生产环境部署:
- 前端构建静态文件:
npm run build - 后端服务托管前端文件:
app.use(express.static('dist'));
身份验证实现(JWT 示例)
后端生成 Token:
const jwt = require('jsonwebtoken');
app.post('/login', (req, res) => {
const token = jwt.sign({ userId: 123 }, 'secret_key', { expiresIn: '1h' });
res.json({ token });
});
前端存储 Token:
localStorage.setItem('token', response.data.token);
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
接口文档规范
使用 Swagger 或 OpenAPI 规范:
paths:
/api/data:
get:
summary: Get data
responses:
200:
description: Successful response
content:
application/json:
schema:
type: object
properties:
message:
type: string






