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

vue express

作者:_o隨缘   发布日期:2025-11-04   浏览:56

// server.js (Express)
const express = require('express');
const app = express();
const port = 3000;

app.use(express.static('public')); // Serve static files from the "public" directory

app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello from Express!' });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

// public/index.html
<!DOCTYPE html>
<html>
<head>
  <title>Vue + Express</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
  <div id="app">
    <h1>{{ message }}</h1>
    <button @click="fetchData">Fetch Data</button>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        message: 'Hello from Vue!'
      },
      methods: {
        async fetchData() {
          try {
            const response = await fetch('/api/data');
            const data = await response.json();
            this.message = data.message;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        }
      }
    });
  </script>
</body>
</html>

解释说明:

  • Express 部分:

    • express.static('public'):将 public 文件夹设置为静态资源目录,用于存放 HTML、CSS 和 JavaScript 文件。
    • /api/data 路由返回一个 JSON 响应,包含一条消息。
    • app.listen 启动服务器并监听指定端口。
  • Vue 部分:

    • index.html 中引入了 Vue.js,并创建了一个简单的 Vue 实例。
    • 页面上有一个按钮,点击后会通过 fetch 请求调用 Express 提供的 API 获取数据,并更新页面上的消息内容。

上一篇:vue3回车键触发事件

下一篇:vue eventbus用法

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue3 router传参

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

Laravel 中文站