Uncaught SyntaxError: Unexpected token {

梦想与她 提交于 2019-12-04 18:34:53

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.

you may try to replace this command

clientResponse.json({});

with

clientResponse.send({});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!