在执行最后一步http://localhost:3000/data/write?type=it&url=xx.com&img=img.xx.com&title=你好 页面显示 The site can't be reached’
在执行请他两个http://localhost:3000/data/read?type=it和http://localhost:3000/data/write?type=it 都没有问题
terminal显示
SyntaxError: Unexpected end of JSON input
at Object.parse (native)
请问是哪里出了问题呢?谢谢
我的代码是
// store data
router.get('/write',function(req, res, next){
// file name
var type = req.param('type')||'';
// data type
var url = req.param('url')||'';
var title = req.param('title')||'';
var img = req.param('img')||'';
var filePath = PATH +type +'.json';
if (!type || !url || !title ||!img){
return res.send({
status:0,
info:'data is not complete'
});
}
// read file
fs.readFile(filePath, function(err, data){
if(err){
return res.send({
status:0,
info:'read data fail'
});
}
var arr = JSON.parse(data.toString());
var obj = {
img:img,
url:url,
title:title,
id: guidGenerate(),
time: new Date()
};
arr.splice(0,0, obj);
// write file
var newData = JSON.stringify(arr);
fs.writeFile(filePath,newData, function(err){
if(err) {
return res.send({
status: 0,
info: 'fail write'
});
}
return res.send({
status:1,
info: obj
});
});
});
});
//guID
function guidGenerate() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase();
}
module.exports = router;