VUE + nodejs实战
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在这个实战中,我们将使用Vue.js和Node.js创建一个简单的前后端分离的应用程序。
后端使用Node.js和Express框架:
const express = require('express');
const app = express();
const port = 3000;
app.get('/api/greeting', (req, res) => {
const name = req.query.name || 'World';
res.json({ message: `Hello, ${name}!` });
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
前端使用Vue.js和axios库发起HTTP请求:
<!-- index.html -->
<div id="app">
<input v-model="name" placeholder="Your name">
<button @click="greet">Greet</button>
<p>{{ message }}</p>
</div>
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
name: '',
message: ''
},
methods: {
greet() {
axios.get('/api/greeting?name=' + encodeURIComponent(this.name))
.then(response => {
this.message = response.data.message;
})
.catch(error => {
console.error('There was an error!', error);
});
}
}
});
</script>
在这个例子中,我们创建了一个简单的前端应用,用户可以输入他们的名字,然后点击一个按钮发送一个GET请求到后端的/api/greeting
路由。后端接收名字,并返回一个问候消息。前端使用Vue的数据绑定显示返回的消息。这个例子演示了前后端通信的基本流程。
评论已关闭