// 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用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站