node vue实现
使用 Node.js 和 Vue.js 实现项目
环境准备
确保已安装 Node.js(建议版本 16+)和 npm/yarn。通过以下命令检查版本:
node -v
npm -v
创建 Vue.js 项目
使用 Vue CLI 快速初始化项目:
npm install -g @vue/cli
vue create my-vue-project
cd my-vue-project
选择默认配置或手动配置(如 Babel、Router、Vuex 等)。
集成 Node.js 后端
在项目根目录创建 server 文件夹作为后端:
mkdir server
cd server
npm init -y
npm install express cors
创建 server/index.js 文件:
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 Node.js backend" });
});
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
前端调用后端 API
在 Vue 项目中,修改 src/App.vue 或组件文件:
<template>
<div>
<button @click="fetchData">Get Data</button>
<p>{{ response }}</p>
</div>
</template>
<script>
export default {
data() {
return {
response: ''
};
},
methods: {
async fetchData() {
const res = await fetch('http://localhost:3001/api/data');
const data = await res.json();
this.response = data.message;
}
}
};
</script>
跨域配置
开发环境下,在 vue.config.js 中配置代理(若无此文件则新建):

module.exports = {
devServer: {
proxy: 'http://localhost:3001'
}
};
启动项目
- 后端启动:
cd server node index.js - 前端启动:
npm run serve
生产部署
- 构建前端代码:
npm run build - 将生成的
dist文件夹内容部署到静态服务器(如 Nginx)。 - 后端可通过 PM2 进程管理工具部署:
npm install -g pm2 pm2 start server/index.js
关键依赖
- 前端:
vue-router、axios(替代fetch)。 - 后端:
express、mongoose(如需数据库)。
通过以上步骤可实现 Node.js 后端与 Vue.js 前端的全栈项目。






