Uncaught SyntaxError: Unexpected token {

2020-07-30 03:36发布

问题:

I am trying to write a chai test where all I do is just stream some audio and get a simple response back: {} , for some reason I'm getting this error Uncaught SyntaxError: Unexpected token { when ever I pipe my fs stream to req, if I remove the piping and I don't have that stream the test works fine.

server code:

router.post('/', function (clientRequest, clientResponse) {
    clientRequest.on('end', function () {//when done streaming audio
        console.log('im at the end>>>>>');
        clientResponse.setHeader('Content-Type', 'application/json'); //I've tried removing that: same result
        clientResponse.json({});
        clientResponse.end(); //I've tried removing that: same result
    }); //end clientRequest.on('end',)
});

test code:

var app = require('./app');

describe('server', function() {
    this.timeout(10000);
    it('should WORK!!!"', function (done){
        var req = chai.request(app).post('/speech');

        var readStream = fs.createReadStream('./test.wav');
        readStream.on('end',function(){
            console.log("readStream end>>>>>>>>>>>>>>>>>>>>>>");
            req.end(function (err, res) {
                console.log("req.end callback>>>>>>>>>>>>>>>");
                done();
            });
        });
        readStream.pipe(req);
    });
});

error:

Uncaught SyntaxError: Unexpected token {
     at Object.parse (native)
     at _stream_readable.js:908:16

回答1:

Error analysis

The code in general is actually works and the problem is somewhere inside the superagent.

Actually question actually is missing some details, so I had to guess missing parts, like chai.request(app) is done using chai-http, which in turn uses superagent to perform http requests.

And the problem seems to be somewhere inside the superagent, I was able to reproduce your error with a bit more info (not sure why I got longer trace):

Uncaught SyntaxError: Unexpected token {                                                                                                                      
 at Object.parse (native)                                                                                                                                     
 at IncomingMessage.<anonymous> (/project/path/node_modules/chai-http/node_modules/superagent/lib/node/parsers/json.js:9:2
 at IncomingMessage.EventEmitter.emit (events.js:117:20)                                                                                                      
 at _stream_readable.js:920:16                                                                                                                                
 at process._tickCallback (node.js:415:13) 

And I was able to check that JSON parses tries to parse double response. Like if server responses with {}, the parser has {}{}, or if server responses with {"a":"b"}, the parser has {"a":"b"}{"a":"b"}. You can check this yourself inserting console.log(res.text) before this line (locally this file is under node_modules/chai-http/node_modules/superagent).

Also if I move the readStream.pipe(req); just above the line with var readStream:

var readStream = fs.createReadStream('./test.wav');
readStream.pipe(req);
readStream.on('end',function(){
    ...

Then the test passes, but outputs 'double callback!' - it is also printed by superagent and confirms that something goes wrong with it.

The fix

It is not complex to do the same thing without chai-http and superagent.

First, the server-side code. It is changed a bit - instead of clientRequest.on('end', ... I pipe it to the write stream. This way I also can check that the file was actually transferred:

var express = require('express');
var fs = require('fs');

var app = express();

module.exports = app;

app.post('/speech', function (clientRequest, clientResponse) {
    console.log('speech');
    var writeStream = fs.createWriteStream('./test_out.wav');
    //for me on('end'... doesn't work (it infinitely waits for event
    //probably because the file is small and it finishes before we
    //get here
    clientRequest.pipe(writeStream).on('finish', function() {
        console.log('im at the end>>>>>');
        clientResponse.json({'a':'b'});
    });
});

app.listen(3000, function() {
  console.log("App started");
});

And the test:

var fs = require('fs');
var chai = require('chai');
var http = require('http');

// Require our application and create a server for it
var app = require('./unexpected');
var server = http.createServer(app);
server.listen(0);
var addr = server.address();

describe('server', function() {
    this.timeout(10000);
    it('should WORK!!!"', function (done){
        // setup read stream
        var readStream = fs.createReadStream('./test.wav');
        readStream.on('end',function(){
            console.log("readStream end>>>>>>>>>>>>>>>>>>>>>>");
        });
        // setup the request
        var request = http.request({
            'host': 'localhost',
            'port': addr.port,
            'path': '/speech',
            'method': 'POST'
        });
        // now pipe the read stream to the request
        readStream.pipe(request).on('finish', function() {
            console.log("pipe end>>>>>>>>>>>>>>>>>>>>>>");
        });
        // get the response and finish when we get all the response data
        request.on('response', function(response) {
            console.log("request end>>>>>>>>>>>>>>>>>>>>>>");
            response.on('data', function(data) {
                console.log('response data: ' + data);
            });
            response.on('end', function(data) {
                console.log('done!');
                done();
            });
        });
    });
});

I think code should be self-explanatory, I just use the standard node http module to do the job.



回答2:

you may try to replace this command

clientResponse.json({});

with

clientResponse.send({});