node vue实现
使用 Node.js 和 Vue.js 实现前后端分离开发
后端部分(Node.js)
安装必要的依赖包:
npm init -y
npm install express body-parser cors
创建 server.js 文件作为后端入口:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const PORT = 3000;
app.get('/api/data', (req, res) => {
res.json({ message: 'Data from Node.js backend' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
前端部分(Vue.js)
使用 Vue CLI 创建项目:
npm install -g @vue/cli
vue create vue-frontend
cd vue-frontend
安装 axios 用于 HTTP 请求:
npm install axios
修改 src/App.vue 文件:
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
message: ''
}
},
created() {
axios.get('http://localhost:3000/api/data')
.then(response => {
this.message = response.data.message;
})
.catch(error => {
console.error(error);
});
}
}
</script>
跨域问题解决方案
在后端 Node.js 应用中已经通过 cors 中间件处理了跨域问题。如果需要更细粒度的控制,可以配置 CORS 选项:
const corsOptions = {
origin: 'http://localhost:8080',
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
项目运行方式
启动后端服务:
node server.js
启动前端开发服务器:
cd vue-frontend
npm run serve
生产环境部署
构建前端生产版本:
npm run build
将生成的 dist 文件夹内容部署到 Web 服务器(如 Nginx),或者与 Node.js 后端集成:
const path = require('path');
app.use(express.static(path.join(__dirname, 'vue-frontend/dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'vue-frontend/dist/index.html'));
});
数据交互增强
实现 POST 请求示例:
后端路由:
app.post('/api/save', (req, res) => {
const data = req.body;
// 处理数据逻辑
res.json({ status: 'success', data });
});
前端调用:

axios.post('http://localhost:3000/api/save', { key: 'value' })
.then(response => {
console.log(response.data);
});
这种架构实现了前后端完全分离,便于独立开发和部署。






