当前位置:首页 > VUE

node vue实现

2026-01-13 23:45:05VUE

使用Node.js和Vue.js实现前后端分离应用

后端(Node.js)搭建 Express框架是Node.js中常用的后端框架,安装Express并创建基础服务器:

npm install express cors

创建server.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 = 3000;
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
npm install axios

修改src/App.vue调用后端API:

<template>
  <div>
    <p>{{ backendData.message }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      backendData: {}
    };
  },
  created() {
    axios.get('http://localhost:3000/api/data')
      .then(response => {
        this.backendData = response.data;
      });
  }
};
</script>

项目联调与跨域处理

后端需配置CORS中间件允许前端访问:

app.use(cors({
  origin: 'http://localhost:8080' // Vue默认开发端口
}));

前端开发服务器代理配置(vue.config.js):

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  }
};

生产环境部署

构建Vue前端静态文件:

npm run build

配置Express托管静态文件:

const path = require('path');
app.use(express.static(path.join(__dirname, 'vue-frontend/dist')));

添加通配路由处理SPA:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'vue-frontend/dist', 'index.html'));
});

数据库集成示例(MongoDB)

安装mongoose连接数据库:

npm install mongoose

数据库连接与模型定义:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb');

const Item = mongoose.model('Item', {
  name: String,
  value: Number
});

app.post('/api/items', async (req, res) => {
  const newItem = new Item(req.body);
  await newItem.save();
  res.status(201).send(newItem);
});

node vue实现

标签: nodevue
分享给朋友:

相关文章

vue实现拖拽

vue实现拖拽

Vue 实现拖拽功能 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来实现。以下是两种常见方法的详细说明: 使用 HTML5 拖拽 A…

vue实现单页面

vue实现单页面

Vue 实现单页面应用(SPA) Vue.js 是一个渐进式框架,非常适合构建单页面应用(SPA)。SPA 的核心特点是整个应用只有一个 HTML 页面,通过动态加载内容实现页面切换,无需重新加载整个…

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <templat…

实现 vue ssr

实现 vue ssr

Vue SSR 实现方法 Vue SSR(Server-Side Rendering)通过服务器端渲染 Vue 应用,提升首屏加载速度和 SEO 友好性。以下是核心实现方法: 基础配置 安装必要依赖…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…