SyntaxError: Unexpected token [Char] in JSON at position 650xx

SyntaxError: Unexpected token [Char] in JSON at position 650xx

当我从我正在构建的 Javascript 应用程序中保存一个 JSON 格式的文件时(运行 它在我本地机器上的 Node v6.11.0 上使用 Express , 端口 3000), 我有时会收到错误:

SyntaxError: JSON 中的意外标记 l 在位置 65032,其中 "token" 是我认为是 JSON 被截断之前的最后一个字符的任何字符,[= =47=] 似乎总是“650xx”,有时低至 65029,有时高至 65036。

当我删除文件中的某些内容以使其可能小于此长度时,它保存得很好,所以这让我相信我正在达到某种默认长度限制,但从哪里开始, 我不能说。我对这个问题所做的搜索似乎表明 JSON 长度的限制至少在 MB 范围内,我保存的最大文件是 104kB。同时,我在 Node.js 中找到的限制,如果有的话,至少也在 MB 范围内。

我正在保存的 JSON 是由以下内容生成的:

var saveCognitionFile = function( filename, content, url ){

    // Attach the camera state so that we can reinstate it at file load.
    attachCameraStateToCognition();

    var httpRequest = new XMLHttpRequest();

    var body = {};
    var jBody;

    if ( url ){
        body.fullpath = url + '/' + filename;       // filename includes ext        
    }           
    else if ( !url || url === "" ){
        body.fullpath = filename; 
    }

    body.data = content;

    jBody = JSON.stringify( body, circRefFilter );

    // Send the request
    httpRequest.open( "POST", '/saveCognition', true );
    httpRequest.setRequestHeader( "Content-Type", "application/json;charset=UTF-8" );
    httpRequest.send( jBody );  

    debug.master && debug.saveCognition && console.log( httpRequest );

    updateUserFilesList();
}; 

其中 circRefFilter 是一个字符串数组,用于过滤发送的 JSON 中包含的 key/value 对。

然后在服务器端,我这样做:

router.post('/saveCognition', function( req, res, next ) { console.log( 'Accessing the Save Cognition route...' );
                        next(); 
                    },
                    function( req, res, next ) { 
                        req.on( 'error', function(){
                            console.log( 'error!' );
                        });
                        req.on( 'data', function( data ) {
                            console.log( 'data at router.post: ', data );

                            var jParsed = JSON.parse( data );
                            console.log( 'data parsed: ', jParsed );

                            jsonMethods.saveCognitionJson( jParsed.fullpath, jParsed.data );
                        });
                        req.on( 'end', function(){
                            console.log( req );
                        });
                        next();
                    },
                    function( req, res ) {
                        res.send('save the current cognition file!'); 
                    } 
                    ); 

考虑到我可能会达到某种 JSON 字符串长度限制,我明白将文件分块发送可能有意义,但我不确定这是否是解决方案,或者如何去做。

感谢帮助。

谢谢!


以下更新以回应 Patrick Evans 的第一个报价。

可能会到达那里但是...我现在遇到错误

TypeError: Cannot read property 'length' of undefined
    at Function.Buffer.concat (buffer.js:304:24)
    at IncomingMessage.<anonymous> (C:\Users\Mark\documents\permiebot\research\experiments\three-js\lucidnodes\routes.js:52:24)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

这是更新后的服务器端代码:

router.post('/saveCognition', function( req, res, next ) { console.log( 'Accessing the Save Cognition route...' );
                        next(); 
                    },
                    function( req, res, next ) { 

                        let reqData = [];
                        let buffer;

                        req.on( 'error', function(){
                            console.log( 'error!' );
                        });
                        req.on( 'data', function( data, chunk ) {

                            reqData.push( chunk );

                            console.log( 'data at router.post: ', data );

                        });
                        req.on( 'end', function(){

                            buffer = Buffer.concat( reqData ).toString();

                            var jParsed = JSON.parse( /* data */ buffer );
                            console.log( 'data parsed: ', jParsed );

                            jsonMethods.saveCognitionJson( jParsed.fullpath, jParsed.data );                            

                            console.log( req );
                        });
                        next();
                    },
                    function( req, res ) {
                        res.send('save the current cognition file!'); 
                    } 
                    );

显然我没有正确连接。删除 .toString() 没有帮助。谢谢。


好吧,第二个错误的更新原来是一个简单的修复。请参阅下面的答案。感谢@PatrickEvans 在评论中提供的帮助。

在@PatrickEvans 对我的问题的评论和此处外部教程的帮助下 https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ 我能够解决这个问题。

正如帕特里克所说:

.on('data'... gets called multiple times (ie your data comes in chunks), keep concatenating data then do the parse in .on('end'

我花了一分钟时间弄清楚如何进行串联,但这是相关的工作服务器端代码。

router.post('/saveCognition', function( req, res, next ) { console.log( 'Accessing the Save Cognition route...' );
                        next(); 
                    },
                    function( req, res, next ) { 

                        let reqData = [];
                        let buffer;

                        req.on( 'error', function(){
                            console.log( 'error!' );
                        });
                        req.on( 'data', function( data ) {

                            reqData.push( data );
                            console.log( 'data at router.post: ', data );

                        });
                        req.on( 'end', function(){

                            buffer = Buffer.concat( reqData ).toString();

                            var jParsed = JSON.parse( buffer );
                            console.log( 'data parsed: ', jParsed );

                            jsonMethods.saveCognitionJson( jParsed.fullpath, jParsed.data );                            

                            console.log( req );
                        });
                        next();
                    },
                    function( req, res ) {
                        res.send('save the current cognition file!'); 
                    } 
                    );