直接使用以下代码
1、前端代码
1.1、html文件,axios直接使用cdn
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>test</title>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<script src="https://unpkg.com/vue@2.6.14/dist/vue.min.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<p>{{ name }}</p>
<span>{{ mana }}</span><span>+{{ speed }}</span>
<p>{{ }}</p>
<button @click="getdata">加载存档</button>
<button @click="savedata">存档</button>
</div>
</body>
</html>
1.2、javascript代码
<script>
//import axios from 'axios'
//const axios = require('axios');
//Vue.prototype.$http=axios
new Vue({
el: '#app',
data: {
name:'无名氏',
message: '斗气大陆',
mana:0,
speed:1
},
methods:{
gradeup:function(){
this.mana+=this.speed
},
getdata:function(){
axios
.get('http://localhost:8888')
.then(response => (this.name = response.data.name,
this.mana = response.data.mana ))
.catch(function (error) { // 请求失败处理
console.log(error);
});
},
savedata:function(){
axios
.get('http://localhost:8888',
{
params: {
req:'save',
mana: this.mana,
name:'萧炎'
}
}
)
// .then(response => (this.name = response.data.name,
// this.mana = response.data.mana ))
// .catch(function (error) { // 请求失败处理
// console.log(error);
// });
}
},
mounted:function(){
setInterval(this.gradeup, 1000);
}
})
</script>
2、后台服务器代码
首先要安装node.js,然后用node.js启动即可
var express = require('express');
var path = require('path');
var fs = require('fs');
var bp = require('body-parser');
var app = express();
app.use(bp.urlencoded({ extended: false }));
//跨域
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS');
res.header('X-Powered-By', 'nodejs');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
//创建get接口
app.get('', (req, res) => {
console.log(req.query); //获取请求参数
var filepath = 'C:\\Users\\wdx\\Desktop\\java+html\\vue\\data.json'; //路径
//读取json文件
fs.readFile(filepath, 'utf-8', function(err, data) {
if (err) {
res.send('文件读取失败');
} else {
res.send(data);
if(req.query.req=='save'){
console.log("保存");
var person = data.toString();
person = JSON.parse(person);
console.log(person);
person.mana=parseInt(req.query.mana);
console.log(req.query.mana);
console.log(person);
var str = JSON.stringify(person);
fs.writeFile('C:\\Users\\wdx\\Desktop\\java+html\\vue\\data.json',str,function(err){
if(err){
console.error(err);
}
console.log('存档成功');
})
}
}
});
});
var host = 'localhost'; //ip
var port = 8888; //端口
app.listen(port, host, () => {
console.log(`http://localhost:8888`);
});
3、json文件
{"name":"萧炎","power":100,"bleed":6000,"mana":1241,"grade":"斗之气","star":1}