node vue实现
Node.js 与 Vue.js 实现方案
后端 Node.js 实现
使用 Express 框架搭建后端服务:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.json());
app.get('/api/data', (req, res) => {
res.json({ message: "Data from Node.js backend" });
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
前端 Vue.js 实现
创建 Vue 项目并添加 Axios 进行数据请求:
// main.js
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
Vue.prototype.$http = axios
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
<!-- App.vue -->
<template>
<div>
<button @click="fetchData">Get Data</button>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
methods: {
async fetchData() {
try {
const res = await this.$http.get('http://localhost:3000/api/data')
this.message = res.data.message
} catch (error) {
console.error(error)
}
}
}
}
</script>
前后端连接配置
在 Vue 项目中创建 vue.config.js 解决跨域问题:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
项目部署方案
使用 PM2 管理 Node.js 进程:
npm install pm2 -g
pm2 start server.js
Vue 项目构建静态文件:
npm run build
将生成的 dist 目录内容部署到 Nginx 或 Apache 服务器。







