Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

nodejs vue

作者:翻成云恨雨愁   发布日期:2025-03-25   浏览:77

// server.js (Node.js 服务器代码)
const express = require('express');
const app = express();
const path = require('path');

// 静态文件中间件,用于提供 Vue 应用的静态文件
app.use(express.static(path.join(__dirname, 'dist')));

// 路由处理
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

// 监听端口
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
<!-- public/index.html (Vue 应用入口文件) -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue App</title>
</head>
<body>
  <div id="app"></div>
  <script src="/js/app.js"></script>
</body>
</html>
// src/main.js (Vue 应用主文件)
import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

解释说明:

  1. Node.js 服务器部分

    • 使用 express 框架创建了一个简单的 HTTP 服务器。
    • express.static 中间件用于提供 Vue 构建后的静态文件(通常在 dist 文件夹中)。
    • 所有路由请求都返回 index.html 文件,确保 Vue Router 的历史模式可以正常工作。
  2. Vue 应用部分

    • index.html 是 Vue 应用的入口文件,包含一个 div 元素作为 Vue 应用的挂载点。
    • main.js 是 Vue 应用的主文件,负责初始化并挂载 Vue 实例到 #app 元素上。

通过这种方式,你可以将 Vue 前端应用与 Node.js 后端服务器结合起来,构建一个完整的全栈应用。

上一篇:vue.filter

下一篇:vue获取日期yyyymmdd

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站