node vue实现增删改查后台代码
时间: 2024-01-06 14:03:22 浏览: 29
好的,以下是一个简单的基于 Node.js 和 Vue.js 的增删改查后台代码示例:
Node.js 后台代码:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(cors());
let items = [
{ id: 1, name: 'item 1' },
{ id: 2, name: 'item 2' },
{ id: 3, name: 'item 3' },
];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
const newItem = { id: items.length + 1, name: req.body.name };
items.push(newItem);
res.json(newItem);
});
app.put('/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const itemIndex = items.findIndex((item) => item.id === itemId);
if (itemIndex >= 0) {
items[itemIndex].name = req.body.name;
res.json(items[itemIndex]);
} else {
res.status(404).send('Item not found');
}
});
app.delete('/items/:id', (req, res) => {
const itemId = parseInt(req.params.id);
const itemIndex = items.findIndex((item) => item.id === itemId);
if (itemIndex >= 0) {
items.splice(itemIndex, 1);
res.status(204).send();
} else {
res.status(404).send('Item not found');
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
```
Vue.js 前端代码:
```html
<template>
<div>
<h1>Items</h1>
<ul>
<li v-for="item in items" :key="item.id">
<input v-model="item.name" @change="updateItem(item)">
<button @click="deleteItem(item)">Delete</button>
</li>
</ul>
<form @submit.prevent="createItem">
<input v-model="newItemName">
<button type="submit">Create</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
newItemName: '',
};
},
mounted() {
this.fetchItems();
},
methods: {
fetchItems() {
fetch('http://localhost:3000/items')
.then((response) => response.json())
.then((items) => (this.items = items));
},
createItem() {
fetch('http://localhost:3000/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: this.newItemName }),
})
.then((response) => response.json())
.then((newItem) => {
this.items.push(newItem);
this.newItemName = '';
});
},
updateItem(item) {
fetch(`http://localhost:3000/items/${item.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: item.name }),
})
.then((response) => response.json())
.catch(() => alert('Failed to update item'));
},
deleteItem(item) {
fetch(`http://localhost:3000/items/${item.id}`, {
method: 'DELETE',
})
.then(() => {
const itemIndex = this.items.indexOf(item);
if (itemIndex >= 0) {
this.items.splice(itemIndex, 1);
}
})
.catch(() => alert('Failed to delete item'));
},
},
};
</script>
```
这个示例实现了一个简单的增删改查功能,你可以根据自己的需求进行修改和扩展。需要注意的是,这个示例没有进行身份验证和授权,如果你用于生产环境,请务必添加相应的安全机制。