请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

SyntaxError: Unexpected end of JSON input

在执行最后一步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;


正在回答

2回答

哔哩哔哩Hong 2016-11-11 15:47:58

我也出现了这个问题,不能把it.json文件全部清空,it.json文件中要写一个空数组 [] ,可以像前面写read一样写个try-catch

1 回复 有任何疑惑可以回复我~
  • 提问者 aroha333 #1
    解决了 谢谢
    回复 有任何疑惑可以回复我~ 2016-11-15 01:42:21
  • Joyer #2
    我写了空数组还是报错,哪里出了问题呢
    回复 有任何疑惑可以回复我~ 2017-04-08 11:52:57
vczero_ 2016-11-07 22:02:41

你好,先对一下代码看看:https://github.com/vczero/toilet。不过我有个疑问:就是,引用/write的文件是什么样的?这个我没办法判断

0 回复 有任何疑惑可以回复我~
  • 提问者 aroha333 #1
    找到原因了, 在json文件中没有放空数组,十分感谢
    回复 有任何疑惑可以回复我~ 2016-11-15 01:43:37
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号