ajax+vue+json数据 动态添加数据到json文件中
时间: 2023-12-10 21:02:39 浏览: 159
要想实现动态添加数据到JSON文件中,需要以下几个步骤:
1. 前端使用Vue和Ajax技术,将需要添加的数据通过POST请求发送到后端。例如:
```javascript
axios.post('/addData', {
name: '张三',
age: 20,
gender: '男'
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```
2. 后端使用Node.js和Express框架接收前端发送的POST请求,并将数据添加到JSON文件中。例如:
```javascript
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/addData', (req, res) => {
const newData = req.body;
const dataFile = './data.json';
let data = [];
fs.readFile(dataFile, 'utf8', (err, content) => {
if (err) {
console.error(err);
res.status(500).send('服务器错误:读取数据文件失败!');
} else {
try {
data = JSON.parse(content);
} catch (e) {
console.error(e);
res.status(500).send('服务器错误:解析数据文件失败!');
}
data.push(newData);
fs.writeFile(dataFile, JSON.stringify(data), err => {
if (err) {
console.error(err);
res.status(500).send('服务器错误:写入数据文件失败!');
} else {
res.send('添加数据成功!');
}
});
}
});
});
app.listen(3000, () => {
console.log('服务器已启动,监听端口3000...');
});
```
在上述代码中,我们首先使用`body-parser`中间件来解析请求体中的JSON数据,然后读取JSON文件中的数据,将新数据添加到数据数组中,最后将修改后的数据数组写回JSON文件中。
注意,以上代码只是一个简单的示例,实际场景中需要添加更多的错误处理和安全措施,例如检查请求体中的数据是否合法、限制JSON文件的大小、防止文件读写冲突等。
阅读全文
相关推荐















