【发布时间】:2019-03-20 00:39:44
【问题描述】:
我正在处理我在本地服务器上托管的项目,我的目标是能够编辑和保存一个 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>
【问题讨论】:
标签: javascript node.js json express vue.js