// 前端 (Vue.js)
<template>
<div>
<button @click="fetchData">获取数据</button>
<p v-if="data">{{ data }}</p>
</div>
</template>
<script>
export default {
data() {
return {
data: null
};
},
methods: {
async fetchData() {
try {
const response = await fetch('http://localhost:3000/api/data');
const result = await response.json();
this.data = result.message;
} catch (error) {
console.error('Error fetching data:', error);
}
}
}
};
</script>
// 后端 (Node.js + Express)
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from the backend!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
前端部分 (Vue.js):
fetch
API 发送 HTTP 请求到后端服务器。fetchData
方法,该方法会发送一个 GET 请求到 /api/data
路由。data
属性中,并在模板中显示。后端部分 (Node.js + Express):
/api/data
,当收到请求时,返回一个 JSON 响应 { message: 'Hello from the backend!' }
。通过这种方式,前端 Vue.js 应用程序可以与后端 Node.js 服务器进行通信。
上一篇:vue loading效果
下一篇:vue.global.js
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站