我正在运行Express Node Server,我使用
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
在服务器上的json中获取数据。带有数据的json看起来像:
[
{
"id": 1453464243666,
"text": "abc"
},
{
"id": 1453464256143,
"text": "def"
},
{
"id": 1453464265564,
"text": "ghi"
}
]
如何(执行什么请求)删除/修改此json中的任何对象?
要读取JSON文件,您可以使用jsonfile模块。然后,您需要put
在快递服务器上定义路由。快递服务器的代码片段突出了重要部分:
app.js
// This assumes you've already installed 'jsonfile' via npm
var jsonfile = require('jsonfile');
// This assumes you've already created an app using Express.
// You'll need to pass the 'id' of the object you need to edit in
// the 'PUT' request from the client.
app.put('/edit/:id', function(req, res) {
var id = req.params.id;
var newText = req.body.text;
// read in the JSON file
jsonfile.readFile('/path/to/file.json', function(err, obj) {
// Using another variable to prevent confusion.
var fileObj = obj;
// Modify the text at the appropriate id
fileObj[id].text = newText;
// Write the modified obj to the file
jsonfile.writeFile('/path/to/file.json', fileObj, function(err) {
if (err) throw err;
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句