在本地服务器上编辑JSON文件

时间:2018-10-15 14:39:24

标签: javascript node.js json express vue.js

我正在处理我在本地服务器上托管的项目,我的目标是能够编辑和保存一个JSON文件,该文件将存储我的项目的配置。我能够读取文件并使用axios请求对其进行访问,但是我对如何通过前端编辑和保存文件感到迷茫。

Server.JS文件

const fs = require('fs');
var userSettings = JSON.parse(fs.readFileSync('config.json'));

var express = require('express');

var app = express();
var server = app.listen(3000, listening);

function listening(){
    console.log("listening ...")
}
app.use(express.static('public'))



app.get('/api/settings', getSettings);
function getSettings(req,res){
    res.send(userSettings)
}

config.json

{
  "CurrentOperation": {
    "numberOfReadingsToBeAveraged": 30,
    "totalNumberOfSensorRunsBeforeRunEnds": 236,
    "waitTimeBetweenSensorReadingsInSeconds": 3342,
    "nameOfDataFileOutput": "DataOutput"
  },
  "Mash": {
    "numberOfReadingsToBeAveraged": 40,
    "totalNumberOfSensorRunsBeforeRunEnds": 203,
    "waitTimeBetweenSensorReadingsInSeconds": 382,
    "nameOfDataFileOutput": "MashOutput"
  },
  "Boil": {
    "numberOfReadingsToBeAveraged": 12,
    "totalNumberOfSensorRunsBeforeRunEnds": 23,
    "waitTimeBetweenSensorReadingsInSeconds": 32,
    "nameOfDataFileOutput": "BoilOutput"
  },
  "Ferment": {
    "numberOfReadingsToBeAveraged": 3,
    "totalNumberOfSensorRunsBeforeRunEnds": 13,
    "waitTimeBetweenSensorReadingsInSeconds": 32,
    "nameOfDataFileOutput": "FermentOutput"
  }
}

位于公共目录中的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Project</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>
<body>
    <div id="app">

        <ul>
            <li v-for="(settings,key) in userSettings">
              {{key}}:{{settings}}
            </li>

        </ul>
      </div>

</body>
<script>
var app = new Vue({
    el: '#app',
    data (){
        return{
            userSettings:'',
        }
    },
    mounted(){
        axios
            .get('api/settings')
            .then(res=>(this.userSettings = res.data))
            .catch(function (error) {
            // handle error
            console.log(error);
  })
    }
  })
</script>
</html>

1 个答案:

答案 0 :(得分:0)

您需要创建一个新端点来接受一个POST请求,该请求将接受您的新配置并触发服务器上文件的重写。

app.post('/api/settings', postSettings);

function postSettings(req,res){
  var fileContent = JSON.stringify(req.body.settings);

  fs.writeFile('config.json', content, 'utf8', function (err) {
    if (err) {
      res.status(400).send({error: 'some error'})
    } else {
      res.send({message: 'success'})
    }
  }); 
}

一些注意事项:

  • 我的上面的代码假设前端将发送一个带有名为settings的对象,其中将包含您要写入的文件的详细信息。

  • 您可能知道这一点,但是建议您将数据存储在数据库中,而不是允许前端在服务器上重写文件